LinkedBlockingQueue 简单使用

简介:LinkedBlockingQueue 是线程安全的实现了先入先出等特性,其中主要用到put和take方法,put方法在队列满的时候会阻塞直到有队列成员被消费,take方法在队列空的时候会阻塞,直到有队列成员被放进来。

 

1.定义方式-->可自定义长度,不定义长度默认为Integer.MAX_VALUE:

(1) final static LinkedBlockingQueue<String> linkQueueOne = new LinkedBlockingQueue<String>();
(2) final static LinkedBlockingQueue<String> linkQueueTwo = new LinkedBlockingQueue<String>(1000);

2.使用:
@Log4j2
public class testLinkedBlockingQueue{
  @Autowired
  private TestService testService;
  public static AtomicInteger b = new AtomicInteger(0);
  public Object linkedBlockingQueue4Add(String arg1) throws Exception {
    //将值放入队列
  linkQueue.put(arg1);
  if(b.get()==0) {
     //相当于返回 ++i
  b.incrementAndGet();
     //处理队列中的数据
  dealQue();
   }
   return null;
  }


   //处理队列中的数据
  private void dealQue() throws InterruptedException {
     new Thread(new Runnable() {
   @Override
   public void run() {
  try {
   log.info("开始处理数据");
            //存放数据
   List<String> addList = new ArrayList<>();
         
           //1000条数据写一次数据库
    for (int i = 0; i < 1000 ; i++) {
     log.debug("加入个数:{}",i);
              //linkQueue.take 当队列中无数据是会阻塞,知道队列中有数据
     addList.add(linkQueue.take());
    }
           //写入数据库操作
    testService.test4BranchAdd(addList);
    log.info("结束处理数据,插入条数:{}",c);
    }catch (Exception e){
   log.info("处理数据异常",e);
  }finally {
           //处理完后将值设置为0
  b.set(0);
  }
   }}).start();
   }
}
AtomicInteger 使用方法见:https://www.cnblogs.com/scuwangjun/p/9098057.html




猜你喜欢

转载自www.cnblogs.com/Mr-xt/p/10069270.html