首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 网络技术 > 网络基础 >

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

2012-10-10 
线程间协作wait()与notify()使用wait()与notify()/notifyAll()可以使得多个任务之间彼此协作?)????? }???

线程间协作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();
????}
}?

?

?

?

热点排行