本文包含兩個演示Java并發(fā)的代碼示例。他們代表非常典型的用法。通過了解他們,您將更好了解notify()和wait()。
1.一些背景知識
- synchronized關(guān)鍵詞用于互斥訪問。
- 為了讓一個方法是同步的,簡單的添加synchronized關(guān)鍵詞到它們的聲明上。那么同一個對象上沒有兩個同步方法的調(diào)用可以相互交錯。
- 同步語句必須指定提供內(nèi)在鎖的對象。當(dāng)使用synchronized(this)時候,必須避免使用同步其他對象方法的調(diào)用。
- wait()告訴調(diào)用的線程放棄監(jiān)視器和進(jìn)入休眠狀態(tài),直到其他線程進(jìn)入相同的監(jiān)視器和調(diào)用notify().
- notify()喚醒在相同對象上第一個調(diào)用wait()的線程。
2. notify()和wait()-例子1
public class ThreadA {
public static void main(String[] args){
ThreadB b = new ThreadB();
b.start();
synchronized(b){
try{
System.out.println("Waiting for b to complete...");
b.wait();
}catch(InterruptedException e){
e.printStackTrace();
}
System.out.println("Total is: " + b.total);
}
}
}
class ThreadB extends Thread{
int total;
@Override
public void run(){
synchronized(this){
for(int i=0; i<100 ; i++){
total += i;
}
notify();
}
}
}
在上面的例子中,一個對象b,被同步。在main線程輸出之前b線程完成計(jì)算。
輸出:
Waiting for b to complete...
Total is: 4950
如果b線程像下面這樣沒有被同步:
public class ThreadA {
public static void main(String[] args) {
ThreadB b = new ThreadB();
b.start();
System.out.println("Total is: " + b.total);
}
}
class ThreadB extends Thread {
int total;
@Override
public void run() {
for (int i = 0; i < 100; i++) {
total += i;
}
}
}
結(jié)果可能是0或10,或其他,因?yàn)閟um在使用之前沒有被計(jì)算完成。
3.notify() 和wait()-例子2
第二個例子更復(fù)雜,看下面注釋:
import java.util.Vector;
class Producer extends Thread {
static final int MAXQUEUE = 5;
private Vector messages = new Vector();
@Override
public void run() {
try {
while (true) {
putMessage();
//sleep(5000);
}
} catch (InterruptedException e) {
}
}
private synchronized void putMessage() throws InterruptedException {
while (messages.size() == MAXQUEUE) {
wait();
}
messages.addElement(new java.util.Date().toString());
System.out.println("put message");
notify();
//Later, when the necessary event happens, the thread that is running it calls notify() from a block synchronized on the same object.
}
// Called by Consumer
public synchronized String getMessage() throws InterruptedException {
notify();
while (messages.size() == 0) {
wait();//By executing wait() from a synchronized block, a thread gives up its hold on the lock and goes to sleep.
}
String message = (String) messages.firstElement();
messages.removeElement(message);
return message;
}
}
class Consumer extends Thread {
Producer producer;
Consumer(Producer p) {
producer = p;
}
@Override
public void run() {
try {
while (true) {
String message = producer.getMessage();
System.out.println("Got message: " + message);
//sleep(200);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
public static void main(String args[]) {
Producer producer = new Producer();
producer.start();
new Consumer(producer).start();
}
}
一個可能的輸出序列:
Got message: Fri Dec 02 21:37:21 EST 2011
put message
put message
put message
put message
put message
Got message: Fri Dec 02 21:37:21 EST 2011
Got message: Fri Dec 02 21:37:21 EST 2011
Got message: Fri Dec 02 21:37:21 EST 2011
Got message: Fri Dec 02 21:37:21 EST 2011
Got message: Fri Dec 02 21:37:21 EST 2011
put message
put message
put message
put message
put message
Got message: Fri Dec 02 21:37:21 EST 2011
Got message: Fri Dec 02 21:37:21 EST 2011
Got message: Fri Dec 02 21:37:21 EST 2011