如何挂起执行直到其他几个线程中的一个完成?换句话说,我只有在完成任何事情时才会继续。谢谢!
答案 0 :(得分:0)
如果使用线程池,则可以使用Future.get()。 当提交任务(Runnable或Callable)时,它返回一个Future实例,你可以使用get()等待任务完成。
e.g。你可以运行下面的例子来了解它是如何工作的。
public static void main(String[] args) throws Exception {
ExecutorService threadPool = Executors.newFixedThreadPool(10);
Semaphore semaphore = new Semaphore(3);
threadPool.submit(new Task(1,1000,semaphore));
threadPool.submit(new Task(2,1000,semaphore));
threadPool.submit(new Task(3,2000,semaphore));
try {
semaphore.acquire();
System.out.println("1 task has finished");
}catch (InterruptedException e){
}
}
public static class Task implements Runnable {
Integer index;
Integer sleep;
Semaphore semaphore;
public Task(Integer index, Integer sleep, Semaphore semaphore) {
this.index = index;
this.sleep = sleep;
this.semaphore = semaphore;
try {
semaphore.acquire();
}catch (InterruptedException e){
semaphore.release();
}
}
@Override
public void run() {
try {
System.out.printf("task %d begin\n", index);
Thread.currentThread().sleep(sleep);
System.out.printf("task %d end\n", index);
semaphore.release();
} catch (InterruptedException e) {
semaphore.release();
}
}
}