美文网首页
线程与异常的结合

线程与异常的结合

作者: 李霖神谷 | 来源:发表于2017-07-31 14:03 被阅读13次
    package com.lishuai.fuxi.www;
    //线程与异常的结合
    //需求:使用线程技术模拟银行存钱,银行对存的钱有限制,超过一定数额就会显示异常
    class Banke {
        static int count = 0;
    
        public void add(int money) {
            count = count + money;
            System.out.println(Thread.currentThread().getName() + "----" + count);
            if(count>=10000){
                throw new GuKe("啦啦啦,你存不了了");
            }
        }
        
    }
    
    class ChuangKou implements Runnable {
        Banke b;
    
        ChuangKou(Banke b) {
            this.b = b;
        }
    
        public void run() {
            // TODO Auto-generated method stub
            while (true) {
                b.add(100);
            }
    
        }
    }
    
    @SuppressWarnings("serial")
    class GuKe extends RuntimeException {
        GuKe(String s) {
            super(s);
        }
    }
    
    public class XianCheng {
    
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            
            try {
                Banke b = new Banke();
                ChuangKou ck = new ChuangKou(b);
                Thread t = new Thread(ck);
                t.start();
            } catch (GuKe g) {
                g.printStackTrace();
                System.err.println(g.toString());
            }
        }
    
    }
    

    相关文章

      网友评论

          本文标题:线程与异常的结合

          本文链接:https://www.haomeiwen.com/subject/aqfrlxtx.html