似懂非懂的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;
                    }
                }
            );
    }
}



你可能感兴趣的:(似懂非懂的SynchronousQueue和长度为1的BlockingQueue)