public class ThreadTest {
public static void main(String[] args) {
//需求:3个生产者线程,负责生产包子,每个线程只能生产一个包子放在桌子上
// 2个消费者线程负责吃包子,每人每次只能从桌子上哪一个包子吃
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();
//创建两个消费者线程
new Thread(() -> {
while (true) {
desk.get();
}
},"吃货1").start();
new Thread(() -> {
while (true) {
desk.get();
}
},"吃货2").start();
}
}
import java.util.ArrayList;
import java.util.List;
public class Desk {
private List<String> list = new ArrayList();
public synchronized void put() {
try {
String name = Thread.currentThread().getName();
if(list.size()==0){
list.add(name+"做的包子");
System.out.println(name+"做了一个包子");
Thread.sleep(2000);
//等待自己,唤醒别人,用当前对象调用 wait(),notify()方法
this.notifyAll();
this.wait();
}else {
//有包子了,不做了
this.notifyAll();
this.wait();
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
public synchronized void get() {
try {
String name = Thread.currentThread().getName();
if(list.size()==1) {
System.out.println(name + list.get(0));
list.clear();
this.notifyAll();
this.wait();
}else{
//没有包子
this.notifyAll();
this.wait();
}
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}