Synchronizing a method is the best way to restrict the use of a method one thread at a time. However, there will be occasions when you won’t be able to synchronize a method, such as when you use a class that is provided to you by a third party. In such cases, you don’t have access to the definition of the class, which prevents you from using the synchronized keyword.
An alternative to using the synchronized keyword is to use the synchronized statement. A synchronized statement contains a synchronized block, within which is placed objects and methods that are to be synchronized. Calls to the methods contained in the synchronized block happen only after the thread enters the monitor of the object.
Although you can call methods within a synchronized block, the method declaration must be made outside a synchronized block.
The following example shows how to use a synchronized statement. This is basically the same as the previous example; however, the synchronized statement is used instead of the synchronized keyword. The synchronized statement is placed in the run() method within the MyThread class. The synchronized statement synchronizes the instance of the Parentheses class and thus prevents two threads from calling the display() method concurrently.
class Parentheses {
void display(String s) {
System.out.print ("(" + s);
try {
Thread.sleep (1000);
} catch (InterruptedException e) {
System.out.println ("Interrupted");
}
System.out.println(")");
}
}
class MyThread implements Runnable {
String s1;
Parentheses p1;
Thread t;
public MyThread (Parentheses p2, String s2) {
p1= p2;
s1= s2;
t = new Thread(this);
t.start();
}
public void run() {
synchronized(p1){
p1.display(s1);
}
}
}
class Demo{
public static void main (String args[]) {
Parentheses p3 = new Parentheses();
MyThread name1 = new MyThread(p3, "Bob");
MyThread name2 = new MyThread(p3, "Mary");
try {
name1.t.join();
name2.t.join();
} catch (InterruptedException e ) {
System.out.println( "Interrupted");
}
}
}
Here, the display() method is not modified by synchronized . Instead, the synchronized statement is used inside the caller’s run() method. This causes the same correct output as before, because each thread waits for the prior one to finish before proceeding.
Communicating Between Threads
Threads have opened programmers to a new dimension in programming, where parts of a program can execute asynchronously, each processing independently of the other. However, sometimes threads have to coordinate their processing and therefore need to be able to communicate with each other during processing. Programmers call this interprocess communication .
You can have threads communicate with each other in your program by using the wait(), notify() , and notifyAll() methods. These methods are called from within a synchronized method. The wait() method tells a thread to relinquish a monitor and go into suspension. There are two forms of the wait() method. One form doesn’t require an argument and causes a thread to wait until it is notified. The other form of the wait() method let’s you specify the amount of time to wait. You specify the length of time in milliseconds, which is passed to the wait() method.
The notify() method tells a thread that is suspended by the wait() method to wake up again and regain control of the monitor. The notifyAll() method wakes up all threads that are waiting for control of the monitor. Only the thread with the highest priority is given control over the monitor. The other threads wait in suspension until the monitor becomes available again.
The following example shows you how to use these methods in an application. The objective of the program is to have the Publisher class give a value to the Consumer class through the use of a Queue class. The Publisher class places a value on the queues and then waits until the Consumer class retrieves the value before the Publisher class places another value on the queue.
This example defines four classes: the Queue class, the Publisher class, the Consumer class, and the Demo class. The Queue class defines two instance values: exchangeValue and a flag. The exchangeValue is used to store the value placed on the queue by the publisher. The flag variable is used as a sign indicating whether a value has been placed on the queue. This is set to false by default, which enables the producer to place a value on to the queue. The Queue class also defines a get() method and a put() method. The put() method is used to place a value on to the queue (that is, to assign a value to the exchangeValue variables). The get() method is used to retrieve the value contained on the queue (that is, to return the value of exchangeValue ). Once the value is assigned, the put() method changes the value of the flag from false to true, indicating there is a value on the queue. Notice how the value of the flag is used within the get() method and the put() method to have the thread that calls the method wait until either there is a value on the queue or there isn’t a value on the queue, depending on which method is being called.
The Publisher class declares an instance of the Queue class and then calls the put() method to place five integers on the queue. Although the put() method is called within a for loop, each integer is placed on the queue and then there is a pause until the integer is retrieved by the Consumer class.
The Consumer class is very similar in design to the Publisher class, except the Consumer class calls the get() method five times from within a for loop. Each call to the get() method is paused until the Publisher class places an integer in the queue.
The main() method of the Demo class creates instances of the Queue class, the Publisher class, and the Consumer class. Notice that both constructors of the Publisher class and the Consumer class are passed a reference to the instance of the same Queue class. They use the instance of the Queue class for inter-process communication .
Here’s what you see when you run this program. Notice that the value placed on the queue by the Publisher is retrieved by the Consumer before the Publisher places the next value on the queue.
Put: 0
Get: 0
Put: 1
Get: 1
Put: 2
Get: 2
Put: 3
Get: 3
Put: 4
Get: 4
class Queue {
int exchangeValue;
boolean busy = false;
synchronized int get() {
if (!busy)
try {
wait();
} catch (InterruptedException e) {
System.out.println(
"Get: InterruptedException");
}
System.out.println("Get: " + exchangeValue);
notify();
return exchangeValue;
}
synchronized void put (int exchangeValue) {
if (busy)
try {
wait();
} catch (InterruptedException e) {
System.out.println(
"Put: InterruptedException");
}
this.exchangeValue = exchangeValue;
busy = true;
System.out.println("Put: " + exchangeValue);
notify();
}
}
class Publisher implements Runnable {
Queue q;
Publisher(Queue q) {
this.q = q;
new Thread (this, "Publisher").start();
}
public void run() {
for (int i = 0; i < 5; i++){
q.put(i);
}
}
}
class Consumer implements Runnable {
Queue q;
Consumer (Queue q) {
this.q = q;
new Thread (this, "Consumer").start();
}
public void run() {
for (int i = 0; i < 5; i++){
q.get();
}
}
}
class Demo {
public static void main(String args []) {
Queue q = new Queue ();
new Publisher (q);
new Consumer (q);
}
}