這是一個計數鎖,說白了,就是當你上鎖的時候,只有計數減少到0的時候,才會釋放鎖 結果 ...
這是一個計數鎖,說白了,就是當你上鎖的時候,只有計數減少到0的時候,才會釋放鎖
package cn.xf.cp.ch05; public class TaskRunable implements Runnable { @Override public void run() { System.out.println("do something..."); } public static void main(String []args) { Thread t = new Thread(new TaskRunable()); t.start(); } }
package cn.xf.cp.ch05; import java.util.concurrent.CountDownLatch; /** * *功能:10個線程同步 *時間:下午6:08:46 *文件:ReadData.java *@author Administrator * */ public class ReadData { // private static int SEEK_NUM = 0; //同步運行,並統計時間 public static long timeTasks(int nThreads, final Runnable task) throws InterruptedException { //起始門,用來劃定線程同步開始的時間 final CountDownLatch startGate = new CountDownLatch(1); //用來等待所有線程結束 final CountDownLatch endGate = new CountDownLatch(nThreads); for(int i = 0; i < nThreads; ++i) { //設置寫出文件開始位置,一個long+空格是10個位元組 //創建線程 Thread t = new Thread() { public void run() { try { //等待所有線程啟動 startGate.await(); try { task.run();//啟動線程 } finally { //線程運行結束之後上通知 endGate.countDown(); } } catch (InterruptedException e) { } } }; t.start(); } long start = System.nanoTime(); //使開始門解鎖,task開始工作 startGate.countDown(); //給end們上鎖,只有減少到0才解鎖 endGate.await(); long end = System.nanoTime(); return end - start; //時間結果 } public static void main(String[] args) { TaskRunable tr = new TaskRunable(); try { System.out.println(ReadData.timeTasks(10, tr)); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } }
結果