首页 > 其他 > 详细

1.SynchronousQueue

时间:2021-04-08 23:46:16      阅读:40      评论:0      收藏:0      [点我收藏+]

来源:package java.util.concurrent;

实现的接口:BlockingQueue

所以它是线程安全的。它的特点是没有内存,因为它的两个常用方法take(),put(),我们去put的时候,如果上次的put没有被take的话,那么它会被阻塞掉,直到上次的put被take掉。

代码案例:

public class SynchronousQueueExample {

  static class SynchronousQueueProducer implements Runnable {

    protected BlockingQueue<String> blockingQueue;

    public SynchronousQueueProducer(BlockingQueue<String> queue) {
      this.blockingQueue = queue;
    }

    @Override
    public void run() {
      while (true) {
        try {
          String data = UUID.randomUUID().toString();
          System.out.println("Put: " + data);
          blockingQueue.put(data);
          Thread.sleep(1000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }

  }

  static class SynchronousQueueConsumer implements Runnable {

    protected BlockingQueue<String> blockingQueue;

    public SynchronousQueueConsumer(BlockingQueue<String> queue) {
      this.blockingQueue = queue;
    }

    @Override
    public void run() {
      while (true) {
        try {
          String data = blockingQueue.take();
          System.out.println(Thread.currentThread().getName()
              + " take(): " + data);
          Thread.sleep(2000);
        } catch (InterruptedException e) {
          e.printStackTrace();
        }
      }
    }

  }

  public static void main(String[] args) {
    final BlockingQueue<String> synchronousQueue = new SynchronousQueue<String>();

    SynchronousQueueProducer queueProducer = new SynchronousQueueProducer(
        synchronousQueue);
    new Thread(queueProducer).start();

    SynchronousQueueConsumer queueConsumer1 = new SynchronousQueueConsumer(
        synchronousQueue);
    new Thread(queueConsumer1).start();

    SynchronousQueueConsumer queueConsumer2 = new SynchronousQueueConsumer(
        synchronousQueue);
    new Thread(queueConsumer2).start();

  }
}

  

运用的场景:缓冲线程池

ExecutorService service2 = Executors.newCachedThreadPool();
--底层实现
public static ExecutorService newCachedThreadPool() {
return new ThreadPoolExecutor(0, Integer.MAX_VALUE,
60L, TimeUnit.SECONDS,
new SynchronousQueue<Runnable>())

说到这里,其他线程池都是有内存容器的,它没内存,也就不会有OOM的情况。

1.SynchronousQueue

原文:https://www.cnblogs.com/johnzhao/p/14635095.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!