有包子 不做了
唤醒别人等地自己
this.notifyAll();
this.wait()
package TheadCpd;
public class TheadCpd {
//目标:了解线程通信
public static void main(String[] args) {
//需求:3个人生产或者线程 负责生产包子 每个线程生产1个包子放桌子上
// 2个消费者线程负责吃包子 每个人每次只能桌子上拿1个包子吃
Desk desk=new Desk();
//创建生产者线程
new Thread(()->{
while (true) {
desk.put();
}
},"厨师1号").start();
new Thread(()->{while (true) {
desk.put();
}
},"厨师2号").start();
new Thread(()->{while (true) {
desk.put();
}
},"厨师3号").start();
//创建2个消费者线程
new Thread(()->{
while (true) {
desk.get();
}
},"吃货1号;").start();
new Thread(()->{
while (true) {
desk.get();
}
},"吃货2号;").start();
}
}
package TheadCpd;
import java.util.ArrayList;
import java.util.List;
public class Desk {
public List<String> list= new ArrayList<>();
//创建1个包子的方法
//三个厨师
public synchronized void put(){
try {
String name=Thread.currentThread().getName();
//判断是否有包子
if (list.size()==0){
list.add(name+"做的肉包子");
System.out.println(name + "做了一个肉包子~~");
Thread.sleep(2000);
//等待
this.notifyAll(); //有包子 不做了
this.wait(); //唤醒别人等地自己
}else {
//有包子 不做了
//唤醒别人等地自己
this.notifyAll();
this.wait();
}
} catch (Exception e) {
e.printStackTrace();
}
}
//两个吃货
public synchronized void get() {
try {
String name= Thread.currentThread().getName();
if (list.size()==1){
//有包子吃
System.out.println(name+"吃了"+list.get(0));
list.clear();
Thread.sleep(1000);
this.notifyAll(); //有包子 不做了
this.wait(); //唤醒别人等地自己
}else{
//没有包子
this.notifyAll(); //有包子 不做了
this.wait(); //唤醒别人等地自己
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}