一个简单的生产者消费者模式,二个线程进行存数据,一个线程进行取数据。
import java.util.concurrent.ArrayBlockingQueue; import java.util.concurrent.BlockingQueue; public class BlockingQueueTest { /** * @param args */ public static void main(String[] args) { final BlockingQueue queue = new ArrayBlockingQueue(3); for (int i = 0; i < 2; i++) { new Thread(new Runnable() { @Override public void run() { while (true) { try { Thread.sleep((long) Math.random() * 1000); System.out.println(Thread.currentThread().getName() + " 准备放数据 "); queue.put(1); System.out.println(Thread.currentThread().getName() + " 队列中有数据 " + queue.size() + " 个"); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); } new Thread(new Runnable() { @Override public void run() { while (true) { try { Thread.sleep((long) Math.random() * 1000); System.out.println(Thread.currentThread().getName() + " 准备取数据 "); queue.take(); System.out.println(Thread.currentThread().getName() + " 队列中剩余数据 " + queue.size() + " 个"); } catch (InterruptedException e) { e.printStackTrace(); } } } }).start(); } }可以自己实际测试一下,可以运行。自己可以查看结果即明白多线程的应用
多线程的并发执行应用(生产者消费者模式),布布扣,bubuko.com
原文地址:http://blog.csdn.net/u012516914/article/details/38690991