原文出处:http://zhangjunhd.blog.51cto.com/113473/71387
比赛类:
package deng;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
/*
* 模拟线程之间的协作。
* Game类有2个同步方法prepare()和go()。
* 标志位start用于判断当前线程是否需要wait()。
* Game类的实例首先启动所有的Athele类实例,使其进入wait()状态,
* 在一段时间后,改变标志位并notifyAll()所有处于wait状态的Athele线程。
*/
public class Game implements Runnable {
private Set<Athlete> players = new HashSet<Athlete>();
private boolean start = false;
//添加运动员
public void addPlayer(Athlete one) {
players.add(one);
}
//删除运动员
public void removePlayer(Athlete one) {
players.remove(one);
}
//获得所有参赛的运动员
public Collection<Athlete> getPlayers() {
return Collections.unmodifiableSet(players);
}
/*
* start为false即比赛没有开始,
* 运动员进入就绪状态
*/
public void prepare(Athlete athlete) throws InterruptedException {
System.out.println(athlete.toString() + " ready!");
synchronized (this) {
while (!start)
wait();//NotifyAll时,start已经为true,即比赛已经开始
if (start)//各运动员开始比赛
System.out.println(athlete + " go!");
}
}
public synchronized void go() {
notifyAll();
}
/*
* 开启Iterator中所有运动员线程
* 让所有的运动员进入就绪待跑状态
*/
public void ready() {
Iterator<Athlete> iter = getPlayers().iterator();
while (iter.hasNext())
new Thread(iter.next()).start();
}
public void run() {
start = false;
System.out.println("Ready......");
System.out.println("Ready......");
System.out.println("Ready......");
//让所有运动员准备就绪
ready();
start = true;
System.out.println("Go!");
go();
}
public static void main(String[] args) {
Game game = new Game();
//准备10个运动员线程
for (int i = 0; i < 10; i++)
game.addPlayer(new Athlete(i, game));
//开始比赛
new Thread(game).start();
}
}
运动员类:
package deng;
import java.util.Collection;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
class Athlete implements Runnable {
private final int id;
private Game game;
public Athlete(int id, Game game) {
this.id = id;
this.game = game;
}
public boolean equals(Object o) {
if (!(o instanceof Athlete))
return false;
Athlete athlete = (Athlete) o;
return id == athlete.id;
}
public String toString() {
return "Athlete<" + id + ">";
}
public int hashCode() {
return new Integer(id).hashCode();
}
public void run() {
try {
game.prepare(this);
} catch (InterruptedException e) {
System.out.println(this + " quit the game");
}
}
}