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);
}
}));
}
}
使用CountDownLatch启动和停止线程
最新推荐文章于 2025-03-19 17:42:40 发布