package org.example;
public class StudyWaitAndNotify {
public static void main(String[] args) {
WorkManNeedToDo a = new WorkMan();
Leader l1 = new Leader(a, 25);
Leader l2 = new Leader(a, 20);
Tester t1 = new Tester(a, 25);
Tester t2 = new Tester(a, 20);
l1.start();
l2.start();
t1.start();
t2.start();
}
}
class Leader extends Thread {
private WorkManNeedToDo workManNeedToDo ;
private int num ;
public Leader (WorkManNeedToDo a, int num){
workManNeedToDo=a;
this.num = num;
}
@Override
public void run() {
workManNeedToDo.getWork(num);
}
}
class Tester extends Thread {
private WorkManNeedToDo workManNeedToDo ;
private int num ;
public Tester (WorkManNeedToDo a, int num){
workManNeedToDo=a;
this.num = num;
}
@Override
public void run() {
workManNeedToDo.doWork(num);
}
}
class WorkMan implements WorkManNeedToDo {
private Object lock = new Object();
private int MAXWORKNUM = 35;// 最多45人天
private int nowWorkNum ;
@Override
public void doWork(int num) {
System.out.println("开始准备工作,当前工作量:"+nowWorkNum+"要完成的工作:"+num);
synchronized (lock){
// nowWorkNum 随时可能边 先锁住
while (num > nowWorkNum){
// 要干的活儿得小于现在有的活儿 先锁住
System.out.println("要干的活儿得小于现在有的活儿 先锁住");
try {
lock.wait();
}catch (Exception e){
e.printStackTrace();
}
}
nowWorkNum = nowWorkNum-num;
System.out.println("工作后,当前工作量:"+nowWorkNum+"已经完成的工作:"+num);
lock.notifyAll();
}
}
@Override
public void getWork(int num) {
System.out.println("开始准备接活儿,当前工作量:"+nowWorkNum+"要接手的工作:"+num);
synchronized (lock){
// nowWorkNum 随时可能变 先锁住
while (num+nowWorkNum > MAXWORKNUM){
// 活儿太多了 没发接 先干完别的再说
System.out.println("活儿太多了 没发接 先干完别的再说");
try {
lock.wait();
}catch (Exception e){
e.printStackTrace();
}
}
nowWorkNum = nowWorkNum+num;
System.out.println("接活后,当前工作量:"+nowWorkNum+"已经接手的工作:"+num);
lock.notifyAll();
}
}
}
interface WorkManNeedToDo {
void doWork(int num);// 工作 减少工作量
void getWork(int num);// 接受任务 增加工作量
}
参考帖子https://www.cnblogs.com/moongeek/p/7631447.html