线程互斥

来源:互联网 发布:宁波淘宝网店培训 编辑:程序博客网 时间:2024/06/08 09:52


public class HuChiThread {
       double balance ;
     public HuChiThread( double money ){
    balance = money;
    System.out.println("余额"+money );
     
     }

public static void main(String[] args) {

HuChiThread t1=new HuChiThread(100);
TestHuiChiThread  t2 = new TestHuiChiThread("ABS",t1,1000);
TestHuiChiThread  t3 = new TestHuiChiThread("ABSC",t1,0);

t2.start();
t3.start();
}




}
class TestHuiChiThread extends Thread {

HuChiThread huChiThread;
int dailytime;

public  TestHuiChiThread(String name ,HuChiThread huChiThread,int dailytime){
this.huChiThread=huChiThread;
this.dailytime=dailytime;

System.out.println("姓名:"+name+",账户:"+this.getName()+",睡眠书剑:"+dailytime);


}
public void  run (){

if (huChiThread.balance >=100){
try {
sleep (dailytime);
huChiThread.balance=huChiThread.balance-100;
System.out.println("取款成功!");
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}



}else  {
System.out.println("失败!");
}

}


}


【结果】

余额100.0
姓名:ABS,账户:Thread-0,睡眠书剑:1000
姓名:ABSC,账户:Thread-1,睡眠书剑:0
取款成功!
取款成功!


原创粉丝点击