多线程模拟生产者消费者示例之BlockQuue

2021-06-15 21:02

阅读:449

}
}

/**
* 生产者
*/
class PThread implements Runnable {
private BlockingQueuequeue;
private AtomicInteger count = new AtomicInteger();

public PThread(BlockingQueue queue) {
this.queue = queue;
}

@Override
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 BlockingQueuequeue;

public CThread(BlockingQueue queue) {
this.queue = queue;
}

@Override
public void run() {
while (true) {
try {
String data = queue.take();
System.out.println("消费数据:"+data);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}


评论


亲,登录后才可以留言!