Start of Tutorial > Start of Trail > Start of Lesson |
Search
Feedback Form |
The preceding sections had a home brewedCubbyHole
data structure to contain the data shared between theProducer
andConsumer
and demonstrated how to use Java synchronization primitives to ensure that the data was accessed in a controlled manner. In your own programs, you probably will want to take advantage of data structures in thejava.util.concurrent
package that hide all the synchronization details.In the following example,
Producer
has been rewritten to use aBlockingQueue
to serve as the cubbyhole. 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.println("Producer #" + number + " put: " + i); sleep((int)(Math.random() * 100)); } catch (InterruptedException e) { } } } }BlockingQueue
version of theConsumer
class is similar. To run the program, useProducerConsumerTest3
, which creates anArrayBlockingQueue
implementation ofBlockingQueue
and passes it to theProducer3
andConsumer3
: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.