首页 > 代码库 > java生产者消费者实例
java生产者消费者实例
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();
}
}
java生产者消费者实例