|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
The preceding sections had a home-brewedCubbyHoledata structure to contain the data shared between theProducerand theConsumer, and they demonstrated how to use Java synchronization primitives to ensure that the data was accessed in a controlled manner. In your programs, you probably will want to take advantage of thejava.util.concurrentpackage's data structures that hide all the synchronization details.In the following example,
Producerhas been rewritten to use aBlockingQueueto serve as thecubbyhole. The queue takes care of all the details of synchronizing access to its contents and notifying other threads of the availability of data.Theimport java.util.concurrent.*; public class Producer3 extends Thread { private BlockingQueue cubbyhole; private int number; public Producer3(BlockingQueue c, int num) { cubbyhole = c; number = num; } public void run() { for (int i = 0; i < 10; i++) { try { cubbyhole.put(i); System.out.format("Producer #%d put: %d%n", number, i); sleep((int)(Math.random() * 100)); } catch (InterruptedException e) { } } } }BlockingQueueversion of theConsumerclass is similar. To run the program, useProducerConsumerTest3, which creates anArrayBlockingQueueimplementation ofBlockingQueueand passes it toProducer3andConsumer3.
import java.util.concurrent.*; public class ProducerConsumerTest3 { public static void main(String[] args) { ArrayBlockingQueue c = new ArrayBlockingQueue(1); Producer3 p1 = new Producer3(c, 1); Consumer3 c1 = new Consumer3(c, 1); p1.start(); c1.start(); } }
|
|
Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.