public class PublicBoxQueue {
static int i = 0;
public static void main(String []args)
{
BlockingQueue BoxQueue= new LinkedBlockingQueue(5); //定义了一个大小为5的盒子
Thread pro= new Thread(new ProducerQueue(BoxQueue));
Thread con= new Thread(new ConsumerQueue(BoxQueue));
pro.start();
con.start();
}
}
//生产者
class ProducerQueue implements Runnable{
private final BlockingQueue proQueue;
public ProducerQueue(BlockingQueue proQueue)
{
this .proQueue =proQueue;
}
@Override
public void run() {
while(true){
try {
PublicBoxQueue.i++;
proQueue.put(PublicBoxQueue.i);
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
//消费者
class ConsumerQueue implements Runnable{
private final BlockingQueue conQueue;
public ConsumerQueue(BlockingQueue conQueue)
{
this .conQueue =conQueue;
}
@Override
public void run() {
while(true){
try {
System.out.print(conQueue.take());
//Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
java 阻塞队列实现生产者和消费者
最新推荐文章于 2023-05-26 08:28:22 发布