在处理业务的时候,往往需要发起多个线程去查询,处理,然后等待所有线程执行完,再进行业务合并处理。
1,CountDownLatch的使用
CountDownLatch更像是一个计数器,可以设置线程数,进行递减。countDownLatch.countDown();线程处理完以后减少,countDownLatch.await();等待所有的线程处理完。举例:
public class CountDownLatchTest {
public static void main(String[] args){
final CountDownLatch countDownLatch = new CountDownLatch(5);
for (int i = 0; i < 5; i++) {
final int no = i;
new Thread(new Runnable() {
@Override
public void run() {
System.out.println(no);
}
}).start();
countDownLatch.countDown();
}
try {
countDownLatch.await();
System.out.println("线程执行完了");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
2,Future的使用
Future结合Callable的使用,线程可以有返回值。举例:
public class FutureTest {
public static void main(String[] args) {
ExecutorService threadPool = Executors.newCachedThreadPool();
List< Future> futureList = new ArrayList Future();
for (int i = 0; i < 5; i++) {
//FutureTask也可以使用
Future future = threadPool.submit(new Callable() {
@Override
public Integer call() throws Exception {
return new Random().nextInt(10);
}
});
futureList.add(future);
}
for (Future f : futureList) {
try {
System.out.println(f.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
}
3.CyclicBarrier比CountDownLatch的使用场景更复杂,自行了解。
本文介绍了三种常用的并发控制工具:CountDownLatch、Future与Callable配合使用的方法,以及CyclicBarrier的基本概念。通过具体示例展示了如何利用这些工具来实现多线程环境下的任务协调与结果收集。

1132

被折叠的 条评论
为什么被折叠?



