let*_*tsc 1 java multithreading
我正在做大学任务(坦率地说).问题是我应该在任何时候运行4个客户端线程(上升数字n).因此,当任何线程终止时,必须生成一个新线程.
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());
}
Run Code Online (Sandbox Code Playgroud)
我想删除忙碌的等待,因为它违背了我的程序的目的.我怎样才能制作主线程wait?(它显示的wait是非静态方法,不能从静态方法调用.)请帮忙.
java.util.concurrent中.CountDownLatch专为您的情况而设计.
限定 CountDownLatch doneSignal = new CountDownLatch(4);
doneSignal.await()将等到doneSignal.countDown()被召唤四次.所以让ClientThreads doneSignal在run()退出时调用相同的 引用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();
Run Code Online (Sandbox Code Playgroud)
嗯 - 你必须手工做,还是你的老师希望你发现Executors.newFixedThreadPool(4)?
这正是具有四个工作线程的线程池所能完成的:不再有四个客户端并行运行,如果一个终止,则free'd工作线程已准备好"获得新工作".
这很简单:
public void test(int threads, int runnables) {
ExecutorsService pool = Executors.newFixedThreadPool(threads);
Runnable r = new Runnable() {
public void run() {
// calculate a factorial or do something else
System.out.println(Thread.currenThread());
}
}
for (int i = 0; i < runnables; i++)
pool.execute(r);
}
Run Code Online (Sandbox Code Playgroud)
让我们runnables大一点threads,你会从结果中看到最多threads数量的线程被(重新)用于执行runnables.