如下所示,product1, product2,product3是三个不同的线程,但由于Producer类里面的成员变量count是静态变量,
所以实际上count是三个线程的共享成员变量,对其进行操作时,最好加上锁访问机制。
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.LinkedBlockingQueue;
public class BlockingQueueTest {
public static void main(String[] args) throws InterruptedException {
// 声明一个容量为10的缓存队列
BlockingQueue<String> queue = new LinkedBlockingQueue<String>(10);
Producer producer1 = new Producer(queue, 1);
Producer producer2 = new Producer(queue, 2);
Producer producer3 = new Producer(queue, 3);
Consumer consumer = new Consumer(queue);
// 借助Executors
ExecutorService service = Executors.newCachedThreadPool();
// 启动线程
service.execute(producer1);
service.execute(producer2);
service.execute(producer3);
// service.execute(consumer);