package Interview;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue;
class 生产者 implements Runnable{
BlockingQueue<String>queue;
public 生产者(BlockingQueue<String> queue){
this.queue=queue;
}
public void run() {
try{
String temp="生产线程:"+Thread.currentThread().getName();
System.out.println("生产:"+Thread.currentThread().getName());
queue.put(temp);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
class 消费者 implements Runnable{
BlockingQueue<String>queue;
public 消费者(BlockingQueue<String>queue){
this.queue=queue;
}
@Override
public void run() {
try {
String temp=queue.take();
System.out.println(temp);
} catch (InterruptedException e) {
// TODO: handle exception
e.printStackTrace();
}
}
}
public class 生产者_消费者 {
public static void main(String[] args) {
// TODO Auto-generated method stub
BlockingQueue<String>queue=new LinkedBlockingQueue<String>(2);
生产者 producer=new 生产者(queue);
消费者 customer=new 消费者(queue);
for(int i=0;i<5;i++){
new Thread(producer,"producer"+(i+1)).start();
new Thread(customer,"customer"+(i+1)).start();
}
}
}
生产者——消费者 blockingqueue实现
最新推荐文章于 2024-11-18 23:29:29 发布