java 多线程 使用CountDownLatch 返回子线程结果
时间: 2023-10-14 12:28:02 浏览: 49
可以使用CountDownLatch配合Future和Callable实现返回子线程的结果。以下是示例代码:
```java
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class ThreadDemo {
public static void main(String[] args) throws InterruptedException, ExecutionException {
ExecutorService executorService = Executors.newCachedThreadPool();
CountDownLatch latch = new CountDownLatch(1);
Future<Integer> future = executorService.submit(new Callable<Integer>() {
@Override
public Integer call() throws Exception {
int result = 0;
// 执行一些耗时的操作
for (int i = 0; i < 1000000; i++) {
result += i;
}
return result;
}
});
new Thread(() -> {
try {
latch.await();
System.out.println("子线程返回结果:" + future.get());
} catch (InterruptedException | ExecutionException e) {
e.printStackTrace();
}
}).start();
// 唤醒等待的子线程
latch.countDown();
executorService.shutdown();
}
}
```
在上面的代码中,我们创建了一个CountDownLatch对象,然后在主线程中启动了一个子线程,子线程执行了一些耗时的操作,返回了结果。在主线程中,我们使用Future对象获取了子线程的返回结果,并且在启动了一个新的线程来处理这个返回结果。在新线程中,我们使用CountDownLatch的await()方法等待主线程调用countDown()方法唤醒它,然后再通过Future的get()方法获取子线程的返回结果。最后,我们调用ExecutorService的shutdown()方法关闭线程池。