2008-07-18
单个线程对多个线程的唤醒
模拟两个线程之间的协作。
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();
}
}
发表评论
- 浏览: 40846 次

- 详细资料
搜索本博客
我的相册
{EADD2367-2334-4234-2434-231181485467}0
共 1 张
共 1 张
链接
- The Tapestry sample applications
- ruby
- Lucene
- Maven 2 简明学习指南(2)
- jsf
- 石头记
- srpingide
- 使用attachment_fu上传
- rails 文件上传
- ruby on rails 实现多文件的上传
- Ruby 多文件上传并写入数据库
- Hibernate Search牛刀小试
- springside分页
- 用Acegi Security来保护Grails应用
- 精通 Grails: 构建您的第一个 Grails 应用程序
- Chinese User Guide
- Rails宝典之第五十二式: 使用Checkbox来更新
- ruby 分页
- ruby 不错的分页
- js效果
- 很多值得看的多线程例子
- web监控
最新评论
-
compass中如何配置分词器 ...
spring配置compass分词器!经过本人多次尝试,以上楼的方法不正确,正确 ...
-- by cslgdxzhangpeng -
在Debian上部署Rails Apac ...
适合我这种新手看.
-- by yangzhihuan -
hibernate usertype 如何 ...
我也了解,确实像楼上说的。现在我想换用jpa,因为他有个@PreRemove @ ...
-- by biaoming -
hibernate usertype 如何 ...
UserType无法得知状态
-- by Quake Wang -
发现一个在线学习groovy的 ...
按照教程,练习了一把,感觉不错。
-- by yf1975






评论排行榜