Java学习——多线程例子:银行

Java学习——多线程例子:银行

package cys;

public class Example9_3 {

    public static void main(String[] args) {
        // TODO Auto-generated method stub
        Bank bank = new Bank();
        bank.setMoney(200);
        Thread thread1,thread2;
        thread1=new Thread(bank);
        thread1.setName("One");
        thread2=new Thread(bank);
        thread2.setName("Two");
        thread1.start();
        thread2.start();
    }

}
class Bank implements Runnable{
    private int number = 0;
    public void setMoney(int m){
        number = m;
    }
    public void run(){
        while(true){
            String name = Thread.currentThread().getName();
            if(name.equals("One")){
                if(number<=80){
                    System.out.println(name + "进入死亡状态");
                    return;
                }
                number = number+10;
                System.out.println("我是Thread"+name + "当前 number="+number);
            }
            
            if(Thread.currentThread().getName().equals("Two")){
                if(number<=0){
                    System.out.println(name+"进入死亡状态");
                    return;
                }
                number=number-100;
                System.out.println("我是Thread"+name+"当前 number="+number);
            }
            try{
                Thread.sleep(800);
            }catch(InterruptedException e){

            }
        
        
    }
    }
}

 
 
 
 
 
 
 
posted on 2018-12-17 17:45 蔡军帅_ACM 阅读(...) 评论(...) 编辑 收藏
原文地址:https://www.cnblogs.com/caiyishuai/p/13270831.html