package entity;
import java.util.ArrayList;
import java.util.List;
public class Queue {
private int maxLen;
private List<Integer> list = new ArrayList<Integer>();
public Queue(int maxLen) {
this.maxLen = maxLen;
}
synchronized public void push(Integer value) {
try {
while (list.size() == maxLen) {
this.wait();
}
list.add(value);
this.notifyAll();
System.out.println(Thread.currentThread().getName() +
" push=" + value + ", List=" + list.toString());
} catch (InterruptedException e) {
e.printStackTrace();
}
}
synchronized public Integer pop() {
Integer value = null;
try {
while (list.size() == 0) {
this.wait();
}
value = list.get(0);
list.remove(0);
this.notifyAll();
System.out.println(Thread.currentThread().getName() +
" pop=" + value + ", List=" + list.toString());
} catch (InterruptedException e) {
e.printStackTrace();
}
return value;
}
}
package thread;
import java.util.Random;
import entity.Queue;
public class Producer extends Thread {
private Queue queue;
public Producer(Queue queue) {
this.queue = queue;
}
@Override
public void run() {
while (true) {
Random r = new Random();
int value = r.nextInt(10) + 100;
queue.push(value);
try {
Thread.sleep(r.nextInt(3)*1000);
}catch(Exception e){}
}
}
}
package thread;
import java.util.Random;
import entity.Queue;
public class Consumer extends Thread {
private Queue queue;
public Consumer(Queue queue) {
this.queue = queue;
}
@Override
public void run() {
while (true) {
queue.pop();
Random r = new Random();
try {
Thread.sleep(r.nextInt(3)*1000);
}catch(Exception e){}
}
}
}
package app;
import entity.Queue;
import thread.Consumer;
import thread.Producer;
public class Main {
public static void main(String[] args) throws InterruptedException{
Queue myQueue = new Queue(5); // set the max length of the queue
for (int i=0;i<6;i++) {
new Producer(myQueue).start();
new Consumer(myQueue).start();
}
}
}
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/32498/viewspace-2641256/ ,如需转载,请注明出处,否则将追究法律责任。