第四章课后作业

4.编写一个程序
public class MyThread extends Thread{

public void run(){
try{
for(int i=1;i<6;i++){
System.out.println(i);
sleep(2000);
}
}
catch(InterruptedException e){}
}
public static void main(String args[]){
System.out.println("当前的线程数:"+Thread.activeCount());
MyThread thread1=new MyThread();
thread1.start();
System.out.println("当前的线程数:"+Thread.activeCount());
MyThread thread2=new MyThread();
thread2.start();
System.out.println("当前的线程数:"+Thread.activeCount());
}
}
5张三和他的妻子各拥有一张银行卡和存折,可以对同一个银行账户进行存取款的操作。现银行账户中余款为500元,每人各取款五次,每次取款100元,在取款过程中存在网络延时。要求使用多线程模拟这个过程。 
 private String name;
 
    public MuRun(String name) {
        this.name = name;
    }
 
    @Override
    public  void run() {
        synchronized(MuRun.class){
        for(int i=0;i<5;i++){
             
            if (test.money > 0) {
                test.money = test.money - 100;
                System.out.println(name + "取走了100元");
            } else {
                System.out.println(name + "没钱了");
            }
            try {
                Thread.sleep(500);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
         
    }
    }
}


Thread zf = new Thread(new MuRun("丈夫"));
        Thread qz = new Thread(new MuRun("妻子"));
            zf.start();
            qz.start();


public class test {
    public static int money = 500;
 
    public static void main(String[] args) {
        Thread zf = new Thread(new MuRun("丈夫"));
        Thread qz = new Thread(new MuRun("妻子"));
            zf.start();
            qz.start();
    }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值