生产者类
import java.util.Queue;
//生产者
public class Producer implements Runnable{
private Queue<String> mylist;
private int maxLen;
public Producer(Queue<String> mylist , int maxLen){
this.mylist = mylist;
this.maxLen = maxLen;
}
@Override
public void run() {
int cursize = 0;
while (true){
cursize ++;
synchronized (mylist){
if(mylist.size() == maxLen){
System.out.println(" 满了");
try {
mylist.wait(); //等待 阻塞当前线程并释放锁
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("生产者生产 book" + cursize);
mylist.add("book" + cursize); //生产
mylist.notify(); // 提示消费者消费
}
}
}
}
消费者类
import java.util.Queue;
public class Consumer implements Runnable{
Queue<String> mylist;
int maxLen;
public Consumer(Queue<String> mylist , int maxLen){
this.mylist = mylist;
this.maxLen = maxLen;
}
@Override
public void run() {
while (true){
synchronized (mylist){
if(mylist.isEmpty()){
System.out.println(" 空了");
try {
mylist.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
try {
Thread.sleep(100);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
String book = mylist.remove();
System.out.println("消费者消费" + book);
mylist.notify();
}
}
}
}
运行
public class ProducerConsumerTest {
public static void main(String[] args) throws InterruptedException {
Queue<String> mylist = new LinkedList<>();
Producer producer = new Producer(mylist,10);
Consumer consumer = new Consumer(mylist,10);
new Thread(producer).start();
Thread.sleep(1000);
new Thread(consumer).start();
}
}