Thread的wait和notify是指的是 Runnable物件而不是 Thread物件,切記,否則喚醒失效

瓜瓜東西發表於2014-07-29
package com.wanju.project001.zonghe.test;


public class TestThreadNotifyWait {


public static void main(String[] args) {
T1 rt1=new T1();
Thread t1 = new Thread(rt1);
Thread t2 = new Thread(new T2(t1));
t1.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// t2.start();
synchronized (rt1) {
for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "----"
+ i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
rt1.notify();
}
// int i=0;
// synchronized (rt1) {
// while (++i <= 10) {
// try {
// Thread.sleep(500);
// System.out.println("The main thread.-->" + i);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
// rt1.notify();
// }

}
}


class T1 implements Runnable {
public void run() {
// synchronized (this) {
// for (int i = 0; i < 10; i++) {
// if (i == 4) {
//
// try {
// this.wait();
// } catch (InterruptedException e) {
// // TODO Auto-generated catch block
// e.printStackTrace();
// }
// // this.notifyAll();
// }
// System.out.println(Thread.currentThread().getName() + "----"
// + i);
// try {
// Thread.sleep(500);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// }
// }

int i = 0;
// 使用物件本身this作為監視器(與主執行緒的監視器為同一個物件)
synchronized (this) {
while (i++ < 20) {
try {
Thread.sleep(500);
System.out.println("The sub thread.-->" + i);
if (i == 10) {
// 釋放監視器鎖,阻塞等待...
this.wait();
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}


}
}


class T2 implements Runnable {
Thread t1;


public T2() {
// TODO Auto-generated constructor stub
}


public T2(Thread t1) {
this.t1 = t1;
}


public void run() {
synchronized (t1) {


for (int i = 0; i < 10; i++) {
System.out.println(Thread.currentThread().getName() + "----"
+ i);
try {
Thread.sleep(500);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
t1.notify();
}
}
}

相關文章