package com.itheima;
class Work implements Runnable{
private int brick = 100;
private int minute = 0;
boolean flag = true;
Object lock = new Object();
public void run(){
while(true) {
synchronized (lock) {
try {
if (brick > 0) {
Thread th = Thread.currentThread();
if (th.getName().equals("张三")) {
System.out.println(th.getName() + "正在搬砖");
Thread.sleep(500);
brick -= 3;
minute += 10;
} else {
Thread ch = Thread.currentThread();
System.out.println(ch.getName() + "正在搬砖");
Thread.sleep(500);
brick -= 5;
minute += 12;
}
}
if (brick <= 0 && flag)
{
System.out.println("搬砖完成,用时" + minute + "分钟");
flag = false;
break;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
public class Main{
public static void main(String[] args){
Work work = new Work();
new Thread(work, "张三").start();
new Thread(work, "李四").start();
}
}
java基础案例8-4工人搬砖
最新推荐文章于 2022-11-10 23:30:00 发布