使用阻塞队列BlockingQueue简单实现生产者消费者

博客直接给出代码,包含消费者类、生产者类,进行了main方法测试,并展示了部分运行结果,聚焦于生产者 - 消费者代码实现。

使用阻塞队列BlockingQueue简单实现生产者消费者

话不多说直接上代码

消费者类

 package com.onecloud.og.server.driver.lumi.test;

import java.util.concurrent.BlockingQueue;

public class Custom implements Runnable{
     
     private final BlockingQueue<Integer> sharedQueue;
     

    public Custom(BlockingQueue<Integer> sharedQueue) {
        this.sharedQueue = sharedQueue;
    }


    @Override
    public void run() {
        for(int i = 0;i<50;i++) {
            try {
                Thread.sleep(200);
                int j = sharedQueue.take();
                System.out.println(Thread.currentThread().getName()+"消费---"+j);
            } catch (InterruptedException e) { 
                 e.printStackTrace();
            }
        }
         
    }

}

生产者类

 package com.onecloud.og.server.driver.lumi.test;

import java.util.concurrent.BlockingQueue;

public class Product implements Runnable{
    
     private final BlockingQueue<Integer> sharedQueue;

     public Product(BlockingQueue<Integer> sharedQueue) {

         this.sharedQueue = sharedQueue;

     }

    @Override
    public void run() {
        for(int i = 0;i<50;i++) { 
            try {
                Thread.sleep(200);
                sharedQueue.put(i);
                System.out.println(Thread.currentThread().getName()+"生产---"+i);
            } catch (InterruptedException e) { 
                 e.printStackTrace();
            }
        }
         
    }

}

main方法测试

 package com.onecloud.og.server.driver.lumi.test;
 
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.LinkedBlockingQueue; 

public class MainTest {
  
     public static void main(String[] args) {
         BlockingQueue<Integer> sharedQueue = new LinkedBlockingQueue<Integer>(); 
         Custom custom = new Custom(sharedQueue);
         Product product = new Product(sharedQueue);
         new Thread(custom).start();
         new Thread(product).start();
     }

}

运行结果(部分)

在这里插Thread-1生产---0
Thread-0消费---0
Thread-0消费---1
Thread-1生产---1
Thread-1生产---2
Thread-0消费---2
Thread-1生产---3
Thread-0消费---3
Thread-1生产---4
Thread-0消费---4
Thread-1生产---5
Thread-0消费---5
Thread-0消费---6
Thread-1生产---6
Thread-1生产---7
Thread-0消费---7
Thread-0消费---8
Thread-1生产---8
Thread-1生产---9
Thread-0消费---9
Thread-1生产---10
Thread-0消费---10
Thread-1生产---11
Thread-0消费---11
Thread-1生产---12
Thread-0消费---12
Thread-1生产---13
入代码片
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值