简单生产者消费者模式

知识点:线程基本通信

生产者:
package com.fengunion.dxc.pc;

import java.util.List;

public class Producer implements Runnable {

private List<String> list;

public Producer(List<String> list) {
this.list = list;
}

@Override
public void run() {
while (true){
synchronized (list){
if(list.size()==1){
System.out.println("队列已满....");
try {
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
list.add("1");
list.forEach(x ->{
System.out.println("生产数据:"+x);
});
list.notify();
}
}
}
}
消费者:
package com.fengunion.dxc.pc;

import java.util.List;

public class Consumer implements Runnable {
private List<String> list;
public Consumer(List<String> list){
this.list=list;
}
@Override
public void run() {
while (true){
synchronized (list){
if(list.size()==0){
System.out.println("队列为空");
try {
list.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}

}
list.forEach(x ->{
System.out.println("消费数据:"+x);
});
list.remove("1");
list.notify();
}
}
}
}
测试:
public static void main(String[] args) {
List<String> list=new ArrayList<>();
Producer p=new Producer(list);
Consumer c = new Consumer(list);
Thread thread = new Thread(p);
Thread thread1 = new Thread(c);
thread.start();
thread1.start();

}
原文地址:https://www.cnblogs.com/coderdxj/p/9708074.html