多线程模拟生产者消费者示例之BlockQuue
2021-06-15 21:02
} /** @Override } /** @Override
}
* 生产者
*/
class PThread implements Runnable {
private BlockingQueue
private AtomicInteger count = new AtomicInteger();
public PThread(BlockingQueue
this.queue = queue;
}
public void run() {
while (true) {
String data = count.getAndIncrement() + "";
System.out.println("生产数据:"+data);
try {
queue.put(data);
Thread.sleep(2000);//sleep,便于观察
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
* 消费者
*/
class CThread implements Runnable {
private BlockingQueue
public CThread(BlockingQueue
this.queue = queue;
}
public void run() {
while (true) {
try {
String data = queue.take();
System.out.println("消费数据:"+data);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}