主要用到的方法是:CountDownLatch,
CountDownLatch类是一个同步倒数计数器,构造时传入int参数,
该参数就是计数器的初始值,
每调用一次countDown()方法,计数器减1,计数器大于0 时,
await()方法会阻塞后面程序执行,直到计数器为0,后面被阻塞的方法才会得以实行。
await(long timeout, TimeUnitunit),是等待一定时间,然后执行,
不管计数器是否到0了。
ublic static void main(String[] args) throws InterruptedException {
CountDownLatch countDownLatch = new CountDownLatch(4);
ExecutorService service = Executors.newFixedThreadPool(6);
DiskMemory diskMemory = new DiskMemory();
for (int i = 0; i < 4; i++) {
service.execute(new Runnable() {
@Override
public void run() {
int timer = new Random().nextInt(5);
try {
Thread.sleep(timer * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
int diskSize = diskMemory.getSize();
System.out.printf("完成磁盘的统计任务,耗费%d秒. 磁盘大小为%d.\n", timer, diskSize);
diskMemory.setSize(diskSize);
// 任务完成之后,计数器减一
countDownLatch.countDown();
System.out.println("count num = " + countDownLatch.getCount());
}
});
}
// 主线程一直被阻塞,直到count的计数器被置为0
countDownLatch.await();
System.out.printf("全部磁盘都统计完成,所有磁盘总大小.\n" + ", totalSize = " + diskMemory.getTotalSize());
service.shutdown();
}
public class DiskMemory {
private int totalSize ;
public int getSize(){
return (new Random().nextInt(3)+1)*100;//加一是为了防止获取磁盘大小为0,不符合常理
}
public void setSize(int size){
totalSize += size;
}
public int getTotalSize(){
return totalSize;
}
}
输出:(count顺序不保证)
完成磁盘的统计任务,耗费0秒. 磁盘大小为300.
count num = 3
完成磁盘的统计任务,耗费2秒. 磁盘大小为100.
count num = 2
完成磁盘的统计任务,耗费2秒. 磁盘大小为300.
count num = 1
完成磁盘的统计任务,耗费2秒. 磁盘大小为300.
count num = 0
全部磁盘都统计完成,所有磁盘总大小 = 1000
网友评论