似懂非懂的SynchronousQueue和长度为1的BlockingQueue

阅读ArrayBlockingQueue源码,很容易知道有界阻塞队列的长度至少为1,也就是至少能缓存下一个数据。长度为0的阻塞队列是没有意义的,因为生产者不能生产,消费者不能消费。但是SynchronousQueue的javadoc文档提到A synchronous queue does not have any internal capacity, not even a capacity of one。也就说同步队列的容量是0,不会缓存数据。

下面的代码片段使用了长度为1的BlockingQueue,可以看到2个生产者有1个会被阻塞(因为队列已满)。

package concurrent;  
  
import java.util.concurrent.ArrayBlockingQueue;  
  
public class TestSynchronousQueue  
{  
      
    private static ArrayBlockingQueue<String> queue = new ArrayBlockingQueue<String>(1);  
  
    public static void main(String[] args) throws Exception   
    {  
        new Productor(1).start();  
        new Productor(2).start();  
        System.out.println("main over.");  
    }  
  
    static class Productor extends Thread  
    {  
        private int id;  
          
        public Productor(int id)  
        {  
            this.id = id;  
        }  
          
        @Override  
        public void run()  
        {  
            try   
            {  
                String result = "id=" + this.id;  
                System.out.println("begin to produce."+result);  
                queue.put(result);  
                System.out.println("success to produce."+result);  
            } catch (InterruptedException e)  
            {  
                e.printStackTrace();  
            }  
        }  
    }  
  
    static class Consumer extends Thread   
    {  
        @Override  
        public void run()  
        {  
            try  
            {  
                System.out.println("consume begin.");  
                String v = queue.take();  
                System.out.println("consume success." + v);  
            } catch (InterruptedException e)  
            {  
                e.printStackTrace();  
            }  
        }  
    }  
}  

这段代码的输出结果如下:

main over.  

begin to produce.id=1  

begin to produce.id=2  

success to produce.id=1  
现在我们将长度为1的阻塞队列换成SynchronousQueue试试看

package concurrent;  
  
import java.util.concurrent.SynchronousQueue;  
  
public class TestSynchronousQueue  
{  
    private static SynchronousQueue<String> queue = new SynchronousQueue<String>();  
  
    public static void main(String[] args) throws Exception   
    {  
        new Productor(1).start();  
        new Productor(2).start();  
        System.out.println("main over.");  
    }  
  
    static class Productor extends Thread  
    {  
        private int id;  
          
        public Productor(int id)  
        {  
            this.id = id;  
        }  
          
        @Override  
        public void run()  
        {  
            try   
            {  
                String result = "id=" + this.id;  
                System.out.println("begin to produce."+result);  
                queue.put(result);  
                System.out.println("success to produce."+result);  
            } catch (InterruptedException e)  
            {  
                e.printStackTrace();  
            }  
        }  
    }  
  
    static class Consumer extends Thread   
    {  
        @Override  
        public void run()  
        {  
            try  
            {  
                System.out.println("consume begin.");  
                String v = queue.take();  
                System.out.println("consume success." + v);  
            } catch (InterruptedException e)  
            {  
                e.printStackTrace();  
            }  
        }  
    }  
}  

这段代码的输出结果如下:可以看到2个生产者线程都被阻塞了,无法进行生产。

main over.  

begin to produce.id=1  

begin to produce.id=2  

 

可以看出SynchronousQueue和BlockingQueue的区别了:在没有消费者的情况下,长度为1的阻塞队列可以让生产者生产1个商品并存储在阻塞队列中;而同步队列不允许生产者进行生产。可以看到同步队列有这样的特性:producer waits until consumer is ready, consumer waits until producer is ready。

 

下面的代码用2个生产者和1个消费者,可以分别使用阻塞队列和同步队列看下输出的情况。

public static void main(String[] args) throws Exception   
{  
    new Consumer().start();  
    Thread.sleep(200);  
  
    new Productor(1).start();  
    new Productor(2).start();  
    System.out.println("main over.");  
}  


 

stackoverflowerror上这篇文章很好地演示了SynchronousQueue的使用场景:

I have a requirement for a task to be executed asynchronously while discarding any further requests until the task is finished.

 

public class SyncQueueTester {  
    private static ExecutorService executor = new ThreadPoolExecutor(1, 1,   
            1000, TimeUnit.SECONDS,   
            new SynchronousQueue<Runnable>(),  
            new ThreadPoolExecutor.DiscardPolicy());  
  
    public static void main(String[] args) throws InterruptedException {  
        for (int i = 0; i < 20; i++) {  
            kickOffEntry(i);  
  
            Thread.sleep(200);  
        }  
  
        executor.shutdown();  
    }  
  
    private static void kickOffEntry(final int index) {  
        executor.  
            submit(  
                new Callable<Void>() {  
                    public Void call() throws InterruptedException {  
                        System.out.println("start " + index);  
                        Thread.sleep(1000); // pretend to do work  
                        System.out.println("stop " + index);  
                        return null;  
                    }  
                }  
            );  
    }  
}  

 

转载于:https://my.oschina.net/weiweiblog/blog/1556635

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值