您的位置:首页 > 产品设计 > UI/UE

java多线程-生产者消费者经典问题 基于BlockingQueue

2016-08-04 11:26 1026 查看
BlockingQueue 可以安全地与多个生产者和多个使用者一起使用

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;

class Producer implements Runnable {
private final BlockingQueue queue;

Producer(BlockingQueue q) {
queue = q;
}

public void run() {
try {
while (true) {
queue.put(produce());
Thread.currentThread().sleep(500);
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}

Object produce() {
System.out.println("produce---" + Thread.currentThread().getName());
return "produce";
}
}

class Consumer implements Runnable {
private final BlockingQueue queue;

Consumer(BlockingQueue q) {
queue = q;
}

public void run() {
try {
while (true) {
consume(queue.take());
Thread.currentThread().sleep(10000);
}
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}

void consume(Object x) {
System.out.println("consume+++" + Thread.currentThread().getName());
}
}

public class Test {
public static void main(String[] args) {
BlockingQueue q = new ArrayBlockingQueue<>(20);
Producer p = new Producer(q);
Consumer c1 = new Consumer(q);
Consumer c2 = new Consumer(q);
new Thread(p).start();
new Thread(c1).start();
new Thread(c2).start();
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息