JAVA閉鎖

壹頁書發表於2014-05-19
JAVA併發程式設計實踐 79頁 閉鎖

設定執行緒的集合點

  1. import java.util.*;
  2. import java.util.concurrent.*;

  3. public class TestHarness{
  4.     public long timeTasks(int nThreads,final Runnable task) throws Exception
  5.     {
  6.         final CountDownLatch startGate=new CountDownLatch(1);
  7.         final CountDownLatch endGate=new CountDownLatch(nThreads);

  8.         for(int i=0;i<nThreads;i++)
  9.         {
  10.             Thread t=new Thread(new Runnable(){
  11.                 public void run()
  12.                 {
  13.                     try{
  14.                         startGate.await();
  15.                         task.run();
  16.                     }
  17.                     catch(Exception ex)
  18.                     {}
  19.                     finally{
  20.                         endGate.countDown();
  21.                     }
  22.                 }
  23.             });
  24.             t.start();
  25.         }

  26.         long start=System.nanoTime();
  27.         startGate.countDown();
  28.         endGate.await();
  29.         long end=System.nanoTime();
  30.         return end-start;
  31.     }

  32.     public static void main(String[] args) throws Exception
  33.     {
  34.         TestHarness t=new TestHarness();
  35.         t.timeTasks(2,new Runnable(){
  36.             public void run(){
  37.                 System.out.println(new Date());
  38.             }
  39.         });
  40.     }
  41. }

來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/29254281/viewspace-1164720/,如需轉載,請註明出處,否則將追究法律責任。

相關文章