在处理业务的时候,往往需要发起多个线程去查询,处理,然后等待所有线程执行完,再进行业务合并处理。
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的使用场景更复杂,自行了解。