日期:2014-05-16  浏览次数:20458 次

Dev-No.01 利用LinkedBlockingQueue实现生产者-消费者模式

? ? 由于LinkedBlockingQueue 实现是线程安全的,实现了先进先出等特性,是作为生产者消费者的首选,LinkedBlockingQueue 可以指定容量,也可以不指定,不指定的话,默认最大是Integer.MAX_VALUE,其中主要用到puttake方法,put方法在队列满的时候会阻塞直到有队列成员被消费,take方法在队列空的时候会阻塞,直到有队列成员被放进来。

?

?

import java.util.UUID;
import java.util.concurrent.*;
/**
	生产者类
*/
public class Producer implements Runnable {
	BlockingQueue<String> queue = new BlockingQueue<String>();
	public Producer(BlockingQueue queue) {
		this.queue = queue;
	}
	public void run() {
		String uuid = UUID.randomUUID ().toString ();
		try {
			queue.put (uuid);
			System.out.println (Thread.currentThread () + “Producer uuid: ” + uuid);
		} cacth (IntterruptedException e) {
			e.printStackTrace ();
		}
	}
}
import java.util.concurrent.*;
/*消费者类*/
public class Consumer implements Runnable {
	BlockingQueue<String> queue = new BlockingQueue<String>();
	public Consumer(BlockingQueue queue) {
		this.queue = queue;
	}
	public void run () {
		try {
			Sting uuid = queue.take ();
			System.out.println (Thread.currentThread () + “Consumer uuid: ” + uuid);
		} catch(IntterruptedException e) {
			e.printStackTrace ();
		}
	}
}

import java.util.concrrent.*;
/*测试类*/
public class TestProducer_Consumer {
	LinkedBlockingQueue<String> queue = new LinkedBlockingQueue<String>(10);
	Producer p1 = new Prodcuer(queue);
	Producer p2 = new Producer(queue);
	Consumer c = new Consumer(queue);

	for(int i=0; i<15; ++i) {
		new Thread(p1).start();
	}
	for(int i=0; i<15; ++i) {
		new Thread(p2).start();
	}
	for(int i=0; i<30; ++i) {
		new Thread(c).start();
	}
}
?

?