单个线程对多个线程的唤醒 博客分类: java Gothread
程序员文章站
2024-02-20 18:04:46
...
模拟两个线程之间的协作。
Athele
类有两个同步方法
prepare()
和
go()
。标志位
start
用于判断当前线程是否需要
wait()
。
Referee
类的实例首先启动所有的
Athele
类实例,使其进入
wait()
状态,在一段时间后,改变标志位并
notifyAll()
所有处于
wait
状态的
Athele
线程。
import java.util.HashSet; import java.util.Iterator; import java.util.Set; import java.util.concurrent.TimeUnit; class Athlete implements Runnable { private boolean start = false; private final int id; public Athlete(int id) { this.id = id; } 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 synchronized void prepare() throws InterruptedException { System.out.println(this + " ready!"); while (start == false) wait(); if (start == true) System.out.println(this + " go!"); } public synchronized void go() { start = true; notifyAll(); } public void run() { try { prepare(); } catch (InterruptedException e) { //maybe should notify the referee System.out.println(this+" quit the game"); } } } class Referee implements Runnable { private Set<Athlete> players = new HashSet<Athlete>(); public void addPlayer(Athlete one) { players.add(one); } public void removePlayer(Athlete one) { players.remove(one); } public void ready() { Iterator<Athlete> iter = players.iterator(); while (iter.hasNext()) new Thread(iter.next()).start(); } public void action() { Iterator<Athlete> iter = players.iterator(); while (iter.hasNext()) iter.next().go(); } public void run() { ready(); try { TimeUnit.SECONDS.sleep(1); } catch (InterruptedException e) { e.printStackTrace(); } action(); } } public class Game { public static void main(String[] args) { Referee referee = new Referee(); for (int i = 0; i < 10; i++) referee.addPlayer(new Athlete(i)); new Thread(referee).start(); } }