並發(三)
阿新 • • 發佈:2017-10-06
rup rand print div 每次 trace time () executor
本篇就是個小的demo,看到了覺得有意思就敲了敲代碼
問題描述:
a,b,c,d四個盤,分別統計出大小,最後要求得四個盤總的大小的值。
首先想到的是CountDownLatch這個類,在所有單個盤的大小統計完成之後,再進行總和的計算。之後,我們需要一個DiskMemory類,抽象盤的大小的統計。有個size和totalSize,大概就這些。啟動線程時,啟動4次,每次分別計算單個的size,最後匯總。
代碼如下:
1 import java.util.Random; 2 3 public class DiskMemory { 4 5 private staticView Codeint 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 importView Codejava.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 17View Code
並發(三)