使用 wiat noify实现
Wiat 会使当前线程进入等待状态 ,其他线程还可以继续运行
Notify 会唤醒当前线程 NotifyAll 会唤醒所有调用该对象的线程
创建生产线程:
@Log4j2
public class Producer implements Runnable {
private List list;
private static int DEFAULT_SIZE = 5;
public Producer(List list) {
this.list = list;
}
@SneakyThrows
public void run() {
synchronized (list) { //给仓库对象list加锁
while (true) {
log.info("进入生产线程....,{}", list.size());
while(DEFAULT_SIZE == list.size()) {
try {
//数据已满等待
log.info("生产线程等待...");
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//一秒生产一个
Thread.sleep(1000);
list.add(list.size());
//唤醒
list.notify();
log.info("生产线程:{}对象数::,{}", Thread.currentThread().getName().toString(), list.size());
}
}
}
}
创建消费线程:
@Log4j2
public class Consumer implements Runnable {
private List list;
public Consumer(List list) {
this.list = list;
}
@SneakyThrows
public void run() {
while (true) {
log.error("进入消费线程...." + list.size());
synchronized (list) { //给仓库对象list加锁
while(list.size() == 0) {
try {
//没有数据等待
log.error("消费线程等待...");
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
//一秒消费一个
Thread.sleep(1000);
Object obj = list.remove(0);
//唤醒
list.notify();
log.error("消费线程消费:{}", obj.toString());
}
}
}
}
调用:
public static void main(String[] args){
new Thread(new Producer(listObj)).start();
new Thread(new Consumer(listObj)).start();
new Thread(new Consumer(listObj)).start();
}