好记性不如铅笔头

java, think_in_java, 编程

《Java编程思想》读书笔记:BlockingQueue

最近在整理 Java 的多线程相关的技术,这里备份下关于【 BlockingQueue 】代码。

github:

https://github.com/cstriker1407/think_in_java 】

BlockingQueueTest.java类:

public class BlockingQueueTest
{
	public static void test()
	{
		BlockingQueue<Integer> queue = new LinkedBlockingDeque<Integer>(10);
		BlockingQueueProducer p1 = new BlockingQueueProducer(queue, 1);

		BlockingQueueConsumer c1 = new BlockingQueueConsumer(queue, 1);
		BlockingQueueConsumer c2 = new BlockingQueueConsumer(queue, 2);
		
		p1.start();
		c1.start();
		c2.start();
	}
}

class BlockingQueueProducer extends Thread
{
	BlockingQueue<Integer> queue;
	int id;
	public BlockingQueueProducer(BlockingQueue<Integer> queue, int id)
	{
		super();
		this.queue = queue;
		this.id = id;
	}

	@Override
	public void run()
	{
		for (int i = 0; i < 100; i++)
		{
			try
			{
				System.out.println("线程ID:" + id + " 生产num:" + i);
				queue.put(i);
			}
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}
			
			try {
				Thread.sleep(1);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

class BlockingQueueConsumer extends Thread
{
	BlockingQueue<Integer> queue;
	int id;

	public BlockingQueueConsumer(BlockingQueue<Integer> queue, int id)
	{
		super();
		this.queue = queue;
		this.id = id;
	}


	@Override
	public void run()
	{
		for (int i = 0; i <50; i++)
		{
			try
			{
				int num = queue.take();
				System.out.println("线程ID:" + id + " 得到的num:" + num);
			}
			catch (InterruptedException e)
			{
				e.printStackTrace();
			}
			
			try {
				Thread.sleep(100);
			} catch (InterruptedException e) {
				e.printStackTrace();
			}
		}
	}
}

 部分日志打印:

线程ID:1 生产num:5
线程ID:1 生产num:6
线程ID:1 生产num:7
线程ID:1 生产num:8
线程ID:1 生产num:9
线程ID:1 生产num:10
线程ID:1 生产num:11
线程ID:1 生产num:12
线程ID:1 得到的num:2
线程ID:1 生产num:13
线程ID:2 得到的num:3
线程ID:1 生产num:14
线程ID:1 得到的num:4

 备注:

这个例子是用 BlockingQueue 实现的消费者-生产者模型,比较简单。

Leave a Reply

2 + 4 =

此站点使用Akismet来减少垃圾评论。了解我们如何处理您的评论数据