生産者消費者java実現
1837 ワード
https://www.b2bchain.cn/6711.html
生産者、消費者デカップリングBUFFERがwait notifyの処理を担当
生産者、消費者デカップリング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 {
//
Queue queue=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;
}
}
}