The JavaTM Tutorial
Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Trail: Essential Java Classes
Lesson: Threads: Doing Two or More Tasks at Once

Synchronized Data Structures

The preceding sections had a home-brewed CubbyHole data structure to contain the data shared between the Producer and the Consumer, 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 the java.util.concurrent package's data structures that hide all the synchronization details.

In the following example, Producer has been rewritten to use a BlockingQueue 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.

import 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) { }
        }
    }
}
The BlockingQueue version of the Consumer class is similar. To run the program, use ProducerConsumerTest3, which creates an ArrayBlockingQueue implementation of BlockingQueue and passes it to Producer3 and Consumer3 (in a .java source file).
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();
    }
}

Previous Page Lesson Contents Next Page Start of Tutorial > Start of Trail > Start of Lesson Search
Feedback Form

Copyright 1995-2005 Sun Microsystems, Inc. All rights reserved.