public static void main(String[] args) throws InterruptedException {
//开始运行时间
long begin = System.currentTimeMillis();
// A 对象内就一个 index 属性
A a = new A();
// new CountDownLatch(你的线程数);
CountDownLatch c = new CountDownLatch(10);
//创建并执行 10 线程
for (int i = 0; i < 10; i++) {
//创建一个执行器
ExecutorService executorService = Executors.newSingleThreadExecutor();
//执行内容
executorService.execute(() ->{
//执行方法
doSomething(a);
//增加栅栏
c.countDown();
});
//执行完关闭
executorService.shutdown();
}
//等待 10 个线程执行完
c.await();
//运行结束耗时
long end = System.currentTimeMillis() - begin;
System.out.println("耗时:" + end +"\n" + "a.index:" + a.index);
}
static void doSomething(A a){
try {
// 模拟运行该方法耗时 1000 毫秒
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 锁住 A 对象 保证在内部计算的值是正确的
// 不加锁的话 index 的值不确定
synchronized (a){
a.index += 1;
System.out.println("执行了一次,当前index:" + a.index);
}
}
java批量执行线程并等待所有线程执行完
最新推荐文章于 2024-06-02 21:10:39 发布