代碼:
//模擬生產(chǎn)和消費(fèi)的對象
class Buffer {
private int maxSize;
private List<Date> storage;
Buffer(int size){
maxSize=size;
storage=new LinkedList<>();
}
//生產(chǎn)方法
public synchronized void put() {
try {
while (storage.size() ==maxSize ){//如果隊(duì)列滿了
System.out.print(Thread.currentThread().getName()+": wait \n");;
wait();//阻塞線程
}
storage.add(new Date());
System.out.print(Thread.currentThread().getName()+": put:"+storage.size()+ "\n");
Thread.sleep(5000);
notifyAll();//喚起線程
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
//消費(fèi)方法
public synchronized void take() {
try {
while (storage.size() == 0){//如果隊(duì)列滿了
System.out.print(Thread.currentThread().getName()+": wait \n");;
wait();//阻塞線程
}
Date d=((LinkedList<Date>)storage).poll();
System.out.print(Thread.currentThread().getName()+": take:"+storage.size()+ "\n");
Thread.sleep(5000);
notifyAll();//喚起線程
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
//生產(chǎn)者
class Producer implements Runnable{
private Buffer buffer;
Producer(Buffer b){
buffer=b;
}
@Override
public void run() {
while(true){
buffer.put();
}
}
}
//消費(fèi)者
class Consumer implements Runnable{
private Buffer buffer;
Consumer(Buffer b){
buffer=b;
}
@Override
public void run() {
while(true){
buffer.take();
}
}
}
public class Main {
public static void main(String[] arg){
Buffer buffer = new Buffer(10);
Producer producer = new Producer(buffer);
Consumer consumer = new Consumer(buffer);
//創(chuàng)建線程執(zhí)行生產(chǎn)和消費(fèi)
for(int i=0;i<3;i++){
new Thread(producer,"producer-"+i).start();
}
for(int i=0;i<3;i++){
new Thread(consumer,"consumer-"+i).start();
}
}
}
執(zhí)行結(jié)果:
producer-0: put:1
producer-0: put:2
consumer-2: take:1
consumer-2: take:0
consumer-2: wait
consumer-1: wait
producer-1: put:1
producer-1: put:2
producer-1: put:3
producer-1: put:4
producer-1: put:5
consumer-0: take:4
consumer-0: take:3
consumer-0: take:2
consumer-0: take:1
consumer-0: take:0
consumer-0: wait
producer-2: put:1
consumer-0: take:0
consumer-0: wait
producer-1: put:1
producer-1: put:2
producer-1: put:3
consumer-1: take:2
consumer-1: take:1
consumer-1: take:0
consumer-1: wait
consumer-2: wait
producer-0: put:1
consumer-2: take:0
consumer-2: wait
consumer-1: wait
producer-1: put:1
producer-1: put:2
producer-1: put:3
producer-1: put:4
producer-1: put:5
consumer-0: take:4
consumer-0: take:3
producer-2: put:4
producer-2: put:5
producer-2: put:6
producer-2: put:7
consumer-0: take:6
consumer-0: take:5
consumer-0: take:4
完畢。