java多线程的实现方式很多,最简单的就是实现Runnable,然后new Thread了,例:
public class Async implements Runnable {
@Override
public void run() {
}
}
public class MainClass {
public void call(){
for(int i=0;i<10;i++){
Async async= new Async();
Thread thread=new Thread(async);
thread.start();
}
}
但是如果需要这10个线程都跑完之后汇总他们的结果呢?这里可以加入CountDownLatch。
public class Async implements Runnable {
private CountDownLatch countDownLatch;
public void setCountDownLatch(CountDownLatch countDownLatch) {
this.countDownLatch = countDownLatch;
}
@Override
public void run() {
//业务逻辑
countDownLatch.countDown();
}
}
public class MainClass {
public void call(){
int size=10;
CountDownLatch ctl = new CountDownLatch(size);
for(int i=0;i<size;i++){
Async async= new Async();
async.setCountDownLatch(ctl);
Thread thread=new Thread(async);
thread.start();
}
ctl.await(6, TimeUnit.SECONDS); //等待多久为超时
}