单个线程对多个线程的唤醒

模拟两个线程之间的协作。 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();
    }
}
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值