读书人

线程间合作wait()与notify()

发布时间: 2012-10-10 13:58:11 作者: rapoo

线程间协作wait()与notify()

使用wait()与notify()/notifyAll()可以使得多个任务之间彼此协作

?

);
????? }
????}
? }

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);
????}

????public void prepare(Athlete athlete) throws InterruptedException {
????? System.out.println(athlete + " ready!");
????? synchronized (this) {
??????? while (!start)
??????? wait();
???? ?? if (start)
???? ?? ? System.out.println(athlete + " go!");
????? }
????}

????public synchronized void go() {
??????notifyAll();
????}
????
????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();
????? for (int i = 0; i < 10; i++)
? ?? ?? game.addPlayer(new Athlete(i, game));
? ? ? new Thread(game).start();
????}
}?

?

?

?

读书人网 >网络基础

热点推荐