Threads often have to coordinate their actions. The most common coordination idiom is the guarded block. Such a block begins by polling a condition that must be true before the block can proceed. There are a number of steps to follow in order to do this correctly.
Suppose, for example guardedJoy
is a method that must not proceed until a shared variable joy
has been set by another thread. Such a method could, in theory, simply loop until the condition is satisfied, but that loop is wasteful, since it executes continuously while waiting.
public void guardedJoy() { // Simple loop guard. Wastes // processor time. Don't do this! while(!joy) {} System.out.println("Joy has been achieved!"); }
A more efficient guard invokes Object.wait
to suspend the current thread. The invocation of wait
does not return until another thread has issued a notification that some special event may have occurred — though not necessarily the event this thread is waiting for:
public synchronized void guardedJoy() { // This guard only loops once for each special event, which may not // be the event we're waiting for. while(!joy) { try { wait(); } catch (InterruptedException e) {} } System.out.println("Joy and efficiency have been achieved!"); }
wait
inside a loop that tests for the condition being waited for. Don't assume that the interrupt was for the particular condition you were waiting for, or that the condition is still true.
Like many methods that suspend execution, wait
can throw InterruptedException
. In this example, we can just ignore that exception — we only care about the value of joy
.
Why is this version of guardedJoy
synchronized? Suppose d
is the object we're using to invoke wait
. When a thread invokesd.wait
, it must own the intrinsic lock for d
— otherwise an error is thrown. Invoking wait
inside a synchronized method is a simple way to acquire the intrinsic lock.
When wait
is invoked, the thread releases the lock and suspends execution. At some future time, another thread will acquire the same lock and invoke Object.notifyAll
, informing all threads waiting on that lock that something important has happened:
public synchronized notifyJoy() { joy = true; notifyAll(); }
Some time after the second thread has released the lock, the first thread reacquires the lock and resumes by returning from the invocation of wait
.
notify
, which wakes up a single thread. Because
notify
doesn't allow you to specify the thread that is woken up, it is useful only in massively parallel applications — that is, programs with a large number of threads, all doing similar chores. In such an application, you don't care which thread gets woken up.
Let's use guarded blocks to create a Producer-Consumer application. This kind of application shares data between two threads: the producer, that creates the data, and the consumer, that does something with it. The two threads communicate using a shared object. Coordination is essential: the consumer thread must not attempt to retrieve the data before the producer thread has delivered it, and the producer thread must not attempt to deliver new data if the consumer hasn't retrieved the old data.
In this example, the data is a series of text messages, which are shared through an object of type
:Drop
public class Drop { // Message sent from producer // to consumer. private String message; // True if consumer should wait // for producer to send message, // false if producer should wait for // consumer to retrieve message. private boolean empty = true; public synchronized String take() { // Wait until message is // available. while (empty) { try { wait(); } catch (InterruptedException e) {} } // Toggle status. empty = true; // Notify producer that // status has changed. notifyAll(); return message; } public synchronized void put(String message) { // Wait until message has // been retrieved. while (!empty) { try { wait(); } catch (InterruptedException e) {} } // Toggle status. empty = false; // Store message. this.message = message; // Notify consumer that status // has changed. notifyAll(); } }
The producer thread, defined in
, sends a series of familiar messages. The string "DONE" indicates that all messages have been sent. To simulate the unpredictable nature of real-world applications, the producer thread pauses for random intervals between messages.Producer
import java.util.Random; public class Producer implements Runnable { private Drop drop; public Producer(Drop drop) { this.drop = drop; } public void run() { String importantInfo[] = { "Mares eat oats", "Does eat oats", "Little lambs eat ivy", "A kid will eat ivy too" }; Random random = new Random(); for (int i = 0; i < importantInfo.length; i++) { drop.put(importantInfo[i]); try { Thread.sleep(random.nextInt(5000)); } catch (InterruptedException e) {} } drop.put("DONE"); } }
The consumer thread, defined in
, simply retrieves the messages and prints them out, until it retrieves the "DONE" string. This thread also pauses for random intervals.Consumer
import java.util.Random; public class Consumer implements Runnable { private Drop drop; public Consumer(Drop drop) { this.drop = drop; } public void run() { Random random = new Random(); for (String message = drop.take(); ! message.equals("DONE"); message = drop.take()) { System.out.format("MESSAGE RECEIVED: %s%n", message); try { Thread.sleep(random.nextInt(5000)); } catch (InterruptedException e) {} } } }
Finally, here is the main thread, defined in
, that launches the producer and consumer threads.ProducerConsumerExample
public class ProducerConsumerExample { public static void main(String[] args) { Drop drop = new Drop(); (new Thread(new Producer(drop))).start(); (new Thread(new Consumer(drop))).start(); } }
Drop
class was written in order to demonstrate guarded blocks. To avoid re-inventing the wheel, examine the existing data structures in the
Java Collections Framework before trying to code your own data-sharing objects. For more information, refer to the
Questions and Exercises section.
1 public void guardedJoy() { 2 // Simple loop guard. Wastes 3 // processor time. Don't do this! 4 while(!joy) {} 5 System.out.println("Joy has been achieved!"); 6 }
一个更加有效率的保护块是在循环中执行Object.wait
方法挂起当前线程。这个线程不会返回直到其他的线程执行了一些特殊的操作并唤醒它,虽然这个线程并不一定在等待。
1 public synchronized void guardedJoy() { 2 // This guard only loops once for each special event, which may not 3 // be the event we're waiting for. 4 while(!joy) { 5 try { 6 wait(); 7 } catch (InterruptedException e) {} 8 } 9 System.out.println("Joy and efficiency have been achieved!"); 10 }
注意:在一个循环中始终执行wait方法在检测是否处于等待状态。不要假定中断一定会发生在你期待的情况下,可能在为真的情况下也出现。
像许多执行挂起的方法一样,wait会抛出InterruptedException异常。在这个实例中我们可以忽视这个异常,我们主要是关心joy的值。
Object.notifyAll
方法。告诉所有的线程,一些重要的事情已经发生了。
1 public synchronized notifyJoy() { 2 joy = true; 3 notifyAll(); 4 }
许多时候当第二个线程释放了这个锁,第一个线程会重新获得锁等待返回调用。
1 public class Drop { 2 // Message sent from producer 3 // to consumer. 4 private String message; 5 // True if consumer should wait 6 // for producer to send message, 7 // false if producer should wait for 8 // consumer to retrieve message. 9 private boolean empty = true; 10 11 public synchronized String take() { 12 // Wait until message is 13 // available. 14 while (empty) { 15 try { 16 wait(); 17 } catch (InterruptedException e) {} 18 } 19 // Toggle status. 20 empty = true; 21 // Notify producer that 22 // status has changed. 23 notifyAll(); 24 return message; 25 } 26 27 public synchronized void put(String message) { 28 // Wait until message has 29 // been retrieved. 30 while (!empty) { 31 try { 32 wait(); 33 } catch (InterruptedException e) {} 34 } 35 // Toggle status. 36 empty = false; 37 // Store message. 38 this.message = message; 39 // Notify consumer that status 40 // has changed. 41 notifyAll(); 42 } 43 }
生产者线程,在producer类中定义,产生一系列相似的消息。“DONE”表示所有的消息都已经发送。为了模拟现实世界的生产者-消费者现象,生产者线程会在发送下一个消息的时候停留随机的时间。
1 import java.util.Random; 2 3 public class Producer implements Runnable { 4 private Drop drop; 5 6 public Producer(Drop drop) { 7 this.drop = drop; 8 } 9 10 public void run() { 11 String importantInfo[] = { 12 "Mares eat oats", 13 "Does eat oats", 14 "Little lambs eat ivy", 15 "A kid will eat ivy too" 16 }; 17 Random random = new Random(); 18 19 for (int i = 0; 20 i < importantInfo.length; 21 i++) { 22 drop.put(importantInfo[i]); 23 try { 24 Thread.sleep(random.nextInt(5000)); 25 } catch (InterruptedException e) {} 26 } 27 drop.put("DONE"); 28 } 29 }
消费者线程,在Consumer类中定义,只是简单的检索和打印这些消息,直到他检索到“DONE”位置,它也会停留随机的时间。
1 import java.util.Random; 2 3 public class Consumer implements Runnable { 4 private Drop drop; 5 6 public Consumer(Drop drop) { 7 this.drop = drop; 8 } 9 10 public void run() { 11 Random random = new Random(); 12 for (String message = drop.take(); 13 ! message.equals("DONE"); 14 message = drop.take()) { 15 System.out.format("MESSAGE RECEIVED: %s%n", message); 16 try { 17 Thread.sleep(random.nextInt(5000)); 18 } catch (InterruptedException e) {} 19 } 20 } 21 }
最后,是主线程,在ProducerConsumerExample线程中定义,它载入了Producer和Consumer类。
1 public class ProducerConsumerExample { 2 public static void main(String[] args) { 3 Drop drop = new Drop(); 4 (new Thread(new Producer(drop))).start(); 5 (new Thread(new Consumer(drop))).start(); 6 } 7 }
注意:写Drop类是为了展示保护块儿。为了避免重复工作,在你编写共享数据类型的时候,请参考已经有的Java Collections Framework。想了解更多详细,请参看Questions and Exercises 节。