Sunday, July 18, 2010

Cooperation

Java's monitor supports two kinds of thread synchronization: mutual exclusion and cooperation . Mutual exclusion, which is supported in the Java virtual machine via object locks, enables multiple threads to independently work on shared data without interfering with each other. Cooperation, which is supported in the Java virtual machine via the wait and notify methods of class Object, enables threads to work together towards a common goal. 

Cooperation is important when one thread needs some data to be in a particular state and another thread is responsible for getting the data into that state. For example, one thread, a "read thread," may be reading data from a buffer that another thread, a "write thread," is filling. The read thread needs the buffer to be in a "not empty" state before it can read any data out of the buffer. If the read thread discovers that the buffer is empty, it must wait. The write thread is responsible for filling the buffer with data. Once the write thread has done some more writing, the read thread can do some more reading. 



Thread Synchronization by Bill Venner





package monitor;
import java.util.Vector;



class Producer extends Thread {
    static final int MAXQUEUE = 5;
    private Vector messages = new Vector(); 
    public void run() {

        try {
         while ( true ) {
                putMessage();
                sleep( 1000 );
            }
        }
        catch( InterruptedException e ) { }
    }

    private synchronized void putMessage() throws InterruptedException {
        while ( messages.size() == MAXQUEUE )
            wait();
        messages.addElement( new java.util.Date().toString() );
        notify();
    }

    // Called by Consumer
    public synchronized String getMessage() throws InterruptedException {
       notify();
       while ( messages.size() == 0 )
            wait();
        String message = (String)messages.firstElement();
        messages.removeElement( message );
        return message;
    }

}



class Consumer extends Thread {
    Producer producer;

    Consumer(Producer p) {
        producer = p;
    }

    public void run() {
        try {
            while ( true ) {
                String message = producer.getMessage();
                System.out.println("Got message: " + message);
                sleep( 2000 );
            }
        }
       catch( InterruptedException e ) { }
    } 
 
    public static void main(String args[]) {
        Producer producer = new Producer();
        producer.start();
        new Consumer( producer ).start();
    }

}
 


No comments:

Post a Comment