标签:countdown main block sleep ace cat return play splay
本篇就是个小的demo,看到了觉得有意思就敲了敲代码
问题描述:
a,b,c,d四个盘,分别统计出大小,最后要求得四个盘总的大小的值。
首先想到的是CountDownLatch这个类,在所有单个盘的大小统计完成之后,再进行总和的计算。之后,我们需要一个DiskMemory类,抽象盘的大小的统计。有个size和totalSize,大概就这些。启动线程时,启动4次,每次分别计算单个的size,最后汇总。
代码如下:
1 import java.util.Random; 2 3 public class DiskMemory { 4 5 private static int totalSize; 6 7 public int getSize() { 8 return new Random().nextInt(5) + 1; 9 } 10 11 public void setSize(int size) { 12 // synchronized method is must 13 synchronized (this) { 14 System.out.println("-------first totalSize: " + totalSize); 15 totalSize = totalSize + size; 16 System.out.println("-------end totalSize: " + totalSize); 17 } 18 19 } 20 21 public int getTotalSize() { 22 return totalSize; 23 } 24 }
1 import java.util.concurrent.CountDownLatch; 2 import java.util.concurrent.ExecutorService; 3 import java.util.concurrent.Executors; 4 import java.util.concurrent.TimeUnit; 5 6 public class CountSizeDemo { 7 8 public static void main(String[] args) { 9 10 CountDownLatch countDownLatch = new CountDownLatch(4); 11 DiskMemory diskMemory = new DiskMemory(); 12 ExecutorService executorService = Executors.newCachedThreadPool(); 13 for (int i = 0; i < 4; i++) { 14 15 executorService.execute(() -> { 16 try { 17 TimeUnit.MICROSECONDS.sleep(1000); 18 } catch (InterruptedException ex) { 19 ex.printStackTrace(); 20 } 21 int size = diskMemory.getSize(); 22 System.out.println("get size: " + size); 23 diskMemory.setSize(size); 24 countDownLatch.countDown(); 25 }); 26 } 27 try { 28 countDownLatch.await(); 29 } catch (InterruptedException e) { 30 // TODO Auto-generated catch block 31 e.printStackTrace(); 32 } 33 System.out.println(diskMemory.getTotalSize()); 34 executorService.shutdownNow(); 35 } 36 37 }
执行结果:
1 get size: 3 2 get size: 4 3 get size: 5 4 get size: 5 5 -------first totalSize: 0 6 -------end totalSize: 3 7 -------first totalSize: 3 8 -------end totalSize: 8 9 -------first totalSize: 8 10 -------end totalSize: 12 11 -------first totalSize: 12 12 -------end totalSize: 17 13 17
标签:countdown main block sleep ace cat return play splay
原文地址:http://www.cnblogs.com/lihao007/p/7630090.html