publicclassProducerimplementsRunnable{private Queue<Integer> queue;
privateint maxSize;
publicProducer(Queue<Integer> queue, int maxSize){
this.queue = queue;
this.maxSize = maxSize;
}
@Overridepublicvoidrun() {
while (true){
synchronized (queue){
while (queue.size() == maxSize){
try{
System.out.println("Queue is Full");
queue.wait();
}catch (InterruptedException ie){
ie.printStackTrace();
}
}
Random random = new Random();
int i = random.nextInt();
System.out.println("Produce " + i);
queue.add(i);
queue.notifyAll();
}
}
}
}
2.2 消费者
publicclassConsumerimplementsRunnable{private Queue<Integer> queue;
privateint maxSize;
publicConsumer(Queue<Integer> queue, int maxSize){
this.queue = queue;
this.maxSize = maxSize;
}
@Overridepublicvoidrun() {
while (true){
synchronized (queue){
while (queue.isEmpty()){
System.out.println("Queue is Empty");
try{
queue.wait();
}catch (InterruptedException ie){
ie.printStackTrace();
}
}
int v = queue.remove();
System.out.println("Consume " + v);
queue.notifyAll();
}
}
}
}
2.3 Main
publicclass Main {
publicstaticvoidmain(String[] args){
Queue<Integer> queue = new LinkedList<>();
int maxSize = 10;
Producer p = new Producer(queue, maxSize);
Consumer c = new Consumer(queue, maxSize);
Thread pT = new Thread(p);
Thread pC = new Thread(c);
pT.start();
pC.start();
}
}