使主线程等待事件 [英] Making main thread wait for an event

查看:86
本文介绍了使主线程等待事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做大学作业(坦率地说).问题是我应该在任何时候运行4个客户端线程(直到数字n).因此,无论何时任何线程终止,都必须产生一个新线程.

I am doing a college assignment(to be frank enough). The problem is that I should have 4 client threads running at any time (uptil a number n). So, whenver any thread terminates, a new thread must be spawned.

  public static void main(String[] args) throws IOException,InterruptedException

   {
     /* some declarations.. */

     ClientThread client=new ClientThread ();

 Runnable intr =client;

 for(count=1;count<=number;count++)

 {
                 /* If 4 client threads has been spawned, wait until 1 of them exits */
           while(Thread.activeCount()<5) 
            ;
            new Thread(intr).start();
   }


       /* Wait until all other threads exits. */
       while(Thread.activeCount()!=1)
        ;   

 System.out.println("\n The sum of factorials is: "+client.getResult());
   }

我想删除繁忙的等待,因为它违反了我程序的目的.我怎样才能使主线程wait? (它显示wait是非静态方法,不能从静态方法中调用.)请帮忙.

I want to remove the busy-waiting as it defeats the very purpose of my program. How can i make the main thread wait ?? (It shows wait is a nonstatic method and cannot be invoked from a static method.) Please help.

推荐答案

java.util.concurrent. CountDownLatch 是针对您的情况设计的.

java.util.concurrent.CountDownLatch is designed for your case.

定义CountDownLatch doneSignal = new CountDownLatch(4);

doneSignal.await()将等到doneSignal.countDown()被调用四次. 因此,让ClientThreads持有相同的引用doneSignal,当run()退出时,调用doneSignal.countDown().

doneSignal.await() will wait until doneSignal.countDown() is called four times. So let ClientThreads hold sames reference doneSignal, when run() exits, call doneSignal.countDown().

class ClientThread implements Runnable {
   private final CountDownLatch doneSignal;
   ClientThread (CountDownLatch doneSignal) {
      this.doneSignal = doneSignal;
   }
   public void run() {
      try {
        //Do something
        doneSignal.countDown();
      } catch (InterruptedException ex) {} 
   }
 }
...
//In main thread
doneSignal.await();

这篇关于使主线程等待事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆