@
woxiangjingjing CountDownLatch 是一个类,要传参数
import java.util.concurrent.*;
public class Count {
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
//定时器要传参数(几个线程完成以后再执行主线程)
CountDownLatch latch = new CountDownLatch(3);
//每个线程要把 CountDownLatch 传进去,每个线程完成以后倒计时-1
A a = new A(latch);
B b = new B(latch);
C c = new C(latch);
Future<Integer> result = executor.submit(a);
Future<Integer> result1 = executor.submit(b);
Future<Integer> result2 = executor.submit(c);
executor.shutdown();
//3 个线程都完成以后就会执行主线程
try {
Thread.sleep(1000);
} catch (InterruptedException e1) {
e1.printStackTrace();
}
System.out.println("主线程在执行任务");
try {
System.out.println("task 运行结果"+result.get()+result1.get()+result2.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("所有任务执行完毕");
}
}
import java.util.concurrent.Callable;
import java.util.concurrent.CountDownLatch;
public class A implements Callable<Integer>{
CountDownLatch latch;
public A(CountDownLatch latch) {
this.latch = latch;
}
@
Override public Integer call() throws Exception {
System.out.println("查询 A 表数据");
Thread.sleep(3000);
int sum = 0;
for(int i=0;i<100;i++)
sum += i;
latch.countDown();
return sum;
}
}
你的 CountDownLatch 用的不对,再看看相关知识吧~