https://www.b2bchain.cn/6711.html
生产者,消费者解耦 BUFFER负责处理 wait notify
package sjms;
import java.util.LinkedList;
import java.util.Queue;
public class product_custom {
public static void main(String[] args) {
buffer b=new buffer();
customer c=new customer(b);
producer p=new producer(b);
c.start();
p.start();
}
//消费者
static class customer extends Thread {
buffer b=new buffer();
customer(buffer b){
this.b=b;
}
public void run(){
for (int i = 0; i <10 ; i++) {
try {
int getval= b.getit();
System.out.println("消费者取得数据"+getval);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//生产者
static class producer extends Thread{
buffer b=new buffer();
producer(buffer b){
this.b=b;
}
public void run(){
for (int i = 0; i <10 ; i++) {
try {
b.add(i);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//缓冲区
static class buffer {
//队列维护
Queuequeue=new LinkedList<>();
int maxsize=5;
public synchronized void add(int val) throws InterruptedException {
if(queue.size()>maxsize) wait();
queue.add(val);
notify();
}
public synchronized int getit() throws InterruptedException {
if(queue.size()==0) wait();
int val= queue.poll();
notify();
return val;
}
}
}