使主线程等待事件

编程入门 行业动态 更新时间:2024-10-28 12:25:53
本文介绍了使主线程等待事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我正在做大学作业(坦率地说).问题是我应该在任何时候运行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();

更多推荐

使主线程等待事件

本文发布于:2023-11-26 22:19:25,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1635429.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:主线   事件

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!