|
|
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 theProducerandConsumerand 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.concurrentpackage that hide all the synchronization details.In the following example,
Producerhas been rewritten to use aBlockingQueueto 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) { } } } }BlockingQueueversion of theConsumerclass is similar. To run the program, useProducerConsumerTest3, which creates anArrayBlockingQueueimplementation ofBlockingQueueand passes it to theProducer3andConsumer3: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.