ew Game();
for (int i = 0; i < 10; i++)
game.addPlayer(new Athlete(i, game));
new Thread(game).start();
}
}
Java中使用wait()与notify()实现线程间协作(2)
时间:2011-03-24 zhangjunhd
结果:
Ready......
Ready......
Ready......
Athlete<0> ready!
Athlete<1> ready!
Athlete<2> ready!
Athlete<3> ready!
Athlete<4> ready!
Athlete<5> ready!
Athlete<6> ready!
Athlete<7> ready!
Athlete<8> ready!
Athlete<9> ready!
Go!
Athlete<9> go!
Athlete<8> go!
Athlete<7> go!
Athlete<6> go!
Athlete<5> go!
Athlete<4> go!
Athlete<3> go!
Athlete<2> go!
Athlete<1> go!
Athlete<0> go!
3.模拟忙等待过程
MyObject类的实例是被观察者,当观察事件发生时,它会通知 一个Monitor类的实例(通知的方式是改变一个标志位)。而此 Monitor类的实例是通过忙等待来不断的检查标志位是否变化。
BusyWaiting.java
import java.util.concurrent.TimeUnit;
class MyObject implements Runnable {
private Monitor monitor;
public MyObject(Monitor monitor) {
this.monitor = monitor;
}
public void run() {
try {
TimeUnit.SECONDS.sleep(3);
System.out.println("i''m going.");
monitor.gotMessage();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Monitor implements Runnable {
private volatile boolean go = false;
public void gotMessage() throws InterruptedException {
go = true;
}
public void watching() {
while (go == false)
;
System.out.println("He has gone.");
}
public void run() {
watching();
}
}
public class BusyWaiting {
public static void main(String[] args) {
Monitor monitor = new Monitor();
MyObject o = new MyObject(monitor);
new Thread(o).start();
new Thread(monitor).start();
}
}
结果:
i''m going.
He has gone.
Java中使用wait()与notify()实现线程间协作(3)
时间:2011-03-24 zhangjunhd
4.使用wait()与notify()改写上面的例子
下面的例子通过wait()来取代忙等待机制,当收到通知消息时 ,notify当前Monitor类线程。
Wait.java
package concurrency.wait;
import java.util.concurrent.TimeUnit;
class MyObject implements Runnable {
private Monitor monitor;
public MyObject(Monitor monitor) {
this.monitor = monitor;
}
public void run() {
try {
TimeUnit.SECONDS.sleep(3);
System.out.println("i''m going.");
monitor.gotMessage();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
class Monitor implements Runnable {
private volatile boolean go = false;
public synchronized void gotMessage() throws InterruptedException {
go = true;
notify();
}
public synchronized void watching() throws InterruptedException {
while (go == false)
wait();
System.out.println("He has gone.");
}
|