1. 程式人生 > >wait();notify();簡單例子

wait();notify();簡單例子

void this () [] status 都是 ron clas wait

public class Test1{

/**
* @param args
*/
public static void main(String[] args) {
new Thread(new Thread1()).start();
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
new Thread(new Thread2()).start();
}

private static class Thread1 implements Runnable {

@Override
public void run() {
// 由於這裏的Thread1和下面的Thread2內部run方法要用同一對象作為監視器,我們這裏不能用this,因為在Thread2裏面的this和這個Thread1的this不是同一個對象。我們用MultiThread.class這個字節碼對象,當前虛擬機裏引用這個變量時,指向的都是同一個對象。
synchronized (Test1.class) {

System.out.println("enter thread1...");
System.out.println("thread1 is waiting");
try {
// 釋放鎖有兩種方式,第一種方式是程序自然離開監視器的範圍,也就是離開了synchronized關鍵字管轄的代碼範圍,另一種方式就是在synchronized關鍵字管轄的代碼內部調用監視器對象的wait方法。這裏,使用wait方法釋放鎖。
Test1.class.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}

System.out.println("thread1 is going on...");
System.out.println("thread1 is being over!");
}
}

}

private static class Thread2 implements Runnable {

@Override
public void run() {
synchronized (Test1.class) {

System.out.println("enter thread2...");
System.out.println("thread2 notify other thread can release wait status..");
// 由於notify方法並不釋放鎖,
// 即使thread2調用下面的sleep方法休息了10毫秒,但thread1仍然不會執行,因為thread2沒有釋放鎖,所以Thread1無法得不到鎖。
//notify並不釋放鎖,只是告訴調用過wait方法的線程可以去參與獲得鎖的競爭了,但不是馬上得到鎖,因為鎖還在別人手裏,別人還沒釋放。如果notify方法後面的代碼還有很多,需要這些代碼執行完後才會釋放鎖
Test1.class.notify();
System.out.println("thread2 is sleeping ten millisecond...");
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("thread2 is going on...");
System.out.println("thread2 is being over!");
}
}

}
}

wait();notify();簡單例子