import java.util.Queue;
import java.util.LinkedList;
public class ProducerConsumerDemo {
public static void main(String[] args) {
MyQueue q = new MyQueue();
Producer p = new Producer(q);
Consumer c = new Consumer(q);
p.start();
c.start();
}
}
class Producer extends Thread {
MyQueue q = new MyQueue();
Producer(MyQueue q) {
this.q = q;
}
public void run() {
int i = 0;
while (true) {
q.push(i);
try {
notify();
} catch (Exception e) {}
System.out.println("producer: " + i);
i++;
}
}
}
class Consumer extends Thread {
MyQueue q = new MyQueue();
Consumer(MyQueue q) {
this.q = q;
}
public void run() {
while (true) {
if (q.size() > 0) {
System.out.println("consumer: " + q.pop());
} else {
try {
wait();
} catch (Exception e) {}
}
}
}
}
class MyQueue {
Queue queue = new LinkedList();
synchronized void push(Object obj) {
queue.offer(obj);
}
synchronized Object pop() {
return queue.poll();
}
long size() {
return queue.size();
}
}
另外一个实例
packagecom.zzz.lcy.dm;importjava.util.LinkedList;importjava.util.concurrent.locks.Condition;importjava.util.concurrent.locks.Lock;importjava.util.concurrent.locks.ReentrantLock;public classTestDataQueue {private LinkedList queue = new LinkedList();private int maxsize = 999;private Lock lock = newReentrantLock();private Condition full =lock.newCondition();private Condition empty =lock.newCondition();public voidput(TestData data) {
lock.lock();while (queue.size() ==maxsize) {try{
full.await();
}catch(InterruptedException e) {
lock.unlock();
}
}
queue.offer(data);
empty.signal();
lock.unlock();
}publicTestData pop() {
lock.lock();while (queue.size() == 0) {try{
empty.await();
}catch(InterruptedException e) {
lock.unlock();
}
}
TestData data=queue.poll();
full.signal();
lock.unlock();returndata;
}public static voidmain(String[] args) {final TestDataQueue q = newTestDataQueue();newThread() {public voidrun() {while (true) {
q.pop();
System.out.println("pop");
}
}
}.start();newThread() {public voidrun() {while (true) {
q.put(null);try{
sleep(1000);
}catch(InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
}
再来一个
importjava.util.concurrent.ArrayBlockingQueue;public classTestDataQueue {private ArrayBlockingQueuequeue;public TestDataQueue(intsize) {
queue= new ArrayBlockingQueue(size);
}publicTestDataQueue() {
queue= new ArrayBlockingQueue(8888);
}public ArrayBlockingQueuegetQueue() {returnqueue;
}public void setQueue(ArrayBlockingQueuequeue) {this.queue =queue;
}public voidput(TestData data) {try{
queue.put(data);
}catch(InterruptedException e) {
e.printStackTrace();
}
}publicTestData pop() {try{returnqueue.take();
}catch(InterruptedException e) {
e.printStackTrace();return null;
}
}
}