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();
}
}
另外一个实例
package com.zzz.lcy.dm; import java.util.LinkedList; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.Lock; import java.util.concurrent.locks.ReentrantLock; public class TestDataQueue { private LinkedList<TestData> queue = new LinkedList<TestData>(); private int maxsize = 999; private Lock lock = new ReentrantLock(); private Condition full = lock.newCondition(); private Condition empty = lock.newCondition(); public void put(TestData data) { lock.lock(); while (queue.size() == maxsize) { try { full.await(); } catch (InterruptedException e) { lock.unlock(); } } queue.offer(data); empty.signal(); lock.unlock(); } public TestData pop() { lock.lock(); while (queue.size() == 0) { try { empty.await(); } catch (InterruptedException e) { lock.unlock(); } } TestData data = queue.poll(); full.signal(); lock.unlock(); return data; } public static void main(String[] args) { final TestDataQueue q = new TestDataQueue(); new Thread() { public void run() { while (true) { q.pop(); System.out.println("pop"); } } }.start(); new Thread() { public void run() { while (true) { q.put(null); try { sleep(1000); } catch (InterruptedException e) { e.printStackTrace(); } } } }.start(); } }
再来一个
import java.util.concurrent.ArrayBlockingQueue; public class TestDataQueue { private ArrayBlockingQueue<TestData> queue; public TestDataQueue(int size) { queue = new ArrayBlockingQueue<TestData>(size); } public TestDataQueue() { queue = new ArrayBlockingQueue<TestData>(8888); } public ArrayBlockingQueue<TestData> getQueue() { return queue; } public void setQueue(ArrayBlockingQueue<TestData> queue) { this.queue = queue; } public void put(TestData data) { try { queue.put(data); } catch (InterruptedException e) { e.printStackTrace(); } } public TestData pop() { try { return queue.take(); } catch (InterruptedException e) { e.printStackTrace(); return null; } } }