问题描述:java实现单生产者、单消费者
思路:利用阻塞队列BlockingQueue,生产者生产数据,进入队列,如果阻塞队列已满,达到最大容量,不能再生产数据,消费者消费数据,出队列,如果阻塞队列没有数据,就不能再消费数据。
代码:
public static void main(String[] args) {
//数组阻塞队列,容量为10
BlockingQueue list=new ArrayBlockingQueue<Integer>(10);
Producer thread1=new Producer(list);
Customer thread2=new Customer(list);
thread1.start(); //启动生产者线程
thread2.start();//启动消费者线程
}
static class Producer extends Thread{
private BlockingQueue<Integer> list;
Producer(BlockingQueue<Integer> list){
this.list=list;
}
@Override
public void run(){
while(true){
try{
int i=new Random().nextInt();
list.put(i);//进入阻塞队列,生产数据
System.out.println("生产数据"+i);
Thread.sleep(200);//控制生产者生产数据的速度
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
static class Customer extends Thread{
private BlockingQueue<Integer> list;
Customer(BlockingQueue<Integer> list ){
this.list=list;
}
@Override
public void run(){
while(true){
try{
int i=list.take();//数据出阻塞队列,消费数据
System.out.println("消费数据"+i);
Thread.sleep(500);//控制消费者消费数据的速度
}catch (InterruptedException e){
e.printStackTrace();
}
}
}
}
参考:https://mp.weixin.qq.com/s/o6SMVqxzdTeWlGmnaW_3-g