使用CountDownLatch啓動和停止線程

package File;

import java.util.concurrent.CountDownLatch;


public class Indexer {
	Indexer(){};
	public long timeTasks(int nThreads,final Runnable stak) throws InterruptedException{
		final CountDownLatch startGate=new CountDownLatch(1);
		final CountDownLatch endGate=new CountDownLatch(nThreads);
		for(int i=0;i<nThreads;i++){
			Thread thread=new Thread(){
				public void run() {
					try {
						startGate.await();//  使當前線程在鎖存器倒計數至零之前一直等待,除非線程被中斷。 關門
						try {
							stak.run();
						} finally {
							endGate.countDown();
						}
					} catch (InterruptedException e) {
						e.printStackTrace();
					}
				}
			};
			thread.start();
		}
		long start=System.nanoTime();
		startGate.countDown();//遞減鎖存器的計數,如果計數到達零,則釋放所有等待的線程。 開門
		endGate.await();
		long end=System.nanoTime();
		return end-start;
		
	}

	
	public static void main(String[] args) throws InterruptedException {
		System.out.println(new Indexer().timeTasks(10, new Runnable() {
			
			@Override
			public void run() {
				System.out.println(1);
				
			}
		}));
	}
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章