进程的互相控制

blueyestar 2009-07-25 07:58:01
class project{
public static void main(String args){
mythread [] thread = new mythread [10];

for(int i=0;i<10;i++){
mythread[i] = new mythread();
mythread[i].start();
}
sleep(100*1000);

thread[0].announce =false;

}

}

class mythread extends Thread{
public boolean announce;
mythread(){
announce =true;
}
public void run(){

while (announce){
....

}

}

程序大概是这个样子, 我想在main 中通知mythread[0] 结束(announce =false), 然后由mythread[0] 通知mythread[1]结束(announce = faluse), mythread[1]中通知 mythread[2]结束,以此类推.

直到mythread[9]结束后 main 才结束 , 这个要怎么写呀?!!
...全文
61 1 打赏 收藏 举报
写回复
用AI写文章
1 条回复
切换为时间正序
请发表友善的回复…
发表回复
hey2009 2009-07-25
  • 打赏
  • 举报
回复

public class project {
public static void main(String[] args) throws Exception {
mythread[] thread = new mythread[10];
for (int i = thread.length-1; i >= 0; i--) {
if (i == thread.length-1) {
thread[i] = new mythread(null);
}else{
thread[i] = new mythread(thread[i + 1]);
}
thread[i].start();
}
Thread.sleep(1000);
thread[0].setAnnounce(false);

}

}

class mythread extends Thread {
public boolean announce;
mythread child = null;
mythread(mythread child) {
this.child = child;//保存下一个线程的引用
announce = true;
}
public void run() {
while (announce) {
System.out.println("===="+this.getName());
}
}
public void setAnnounce(boolean announce){
System.out.println("-------------------------------");
this.announce = announce;
if(child!=null)
child.setAnnounce(announce);
}
}

62,620

社区成员

发帖
与我相关
我的任务
社区描述
Java 2 Standard Edition
社区管理员
  • Java SE
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧