并发

xiaoxiao2021-03-01  17

final int total = 3; ExecutorService executors = Executors.newScheduledThreadPool(total); final CountDownLatch c = CountDownLatch(total); //CountDownLatch 是一个同步工具,用来协调多个线程之间的同步 ,或者线程之间的通信 //用法:某一个线程开始运行前等待n个线程执行完毕。每当一个任务线程执行完毕,就将计数器减1,当计数器的值变为0时,在CountDownLatch的await()的线程就会被唤醒 final AtomicInteger ai = new AtomicInteger(0); for(int i=0;i<total;i++){ executors.execute(new Runnable(){ @Override public void run(){ Long currentTime = System.currentTimeMillis(); //do something Long spendTime = System.currentTimeMills() - currentTime; log.info(new Date()+":"+ai.incrementAndGet()+" threads have done!"); c.countDown(); } }); } try{ c.await(); log.info("............") executors.shutdown(); }catch(InterruptedException e){ log.info(e) }
转载请注明原文地址: https://www.6miu.com/read-3650161.html

最新回复(0)