ITPub博客

首页 > 应用开发 > Java > JAVA闭锁

JAVA闭锁

Java 作者:壹頁書 时间:2014-05-19 23:58:17 0 删除 编辑
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博客 ” ,链接:https://blog.itpub.net/29254281/viewspace-1164720/ ,如需转载,请注明出处,否则将追究法律责任。

上一篇: JAVA信号量
下一篇: JAVA栅栏
请登录后发表评论 登录
全部评论

注册时间:2013-10-19

  • 博文量
    620
  • 访问量
    6339970