闭锁
1.定义:
闭锁是一种同步工具,可以延迟线程直到其达到其终止状态。
例如:DOTA2中匹配等待点确定界面的设计,需要等待所有十个玩家都点就绪才能继续进行。其实也有些类似于之前CUDA编程中用到的 __syncthreads()方法去同步同一个块内的线程。
2.实现
CountDownLatch是一种灵活的闭锁实现。一般会把StartGate设置1,EndGate设置为nThreads。通过await()方法等待计数器减到0,countdown()方法执行计数器减法。
3.代码
书本TestHarness类
import java.util.concurrent.CountDownLatch;
public class TestHarness {
public long timetasks(int nThreads, final Runnable task) throws InterruptedException {
// init start from 1.
final CountDownLatch startGate = new CountDownLatch(1);
final CountDownLatch endGate = new CountDownLatch(nThreads);
for (int i=0;i< nThreads;i++){
Thread t = new Thread(){
public void run(){
try{
startGate.await();//wait the startgate count down to zero, then run.
try{
task.run();
} finally {
endGate.countDown();
}
} catch (InterruptedException ignored){ }
}
};
t.start();
}
long start = System.nanoTime(); //单位纳秒
startGate.countDown();
endGate.await();//wait the endGate count down to zero, then run.
long end = System.nanoTime();
return end - start;
}
}
我写的测试类
public class Solution {
public static void main(String[] args) throws InterruptedException {
final Thread tt = new Thread(){
@Override
public void run() {
System.out.println("Thread Id: " + this.getId()); //具体的方法,比如DOTA2中点击准备就绪的按键
}
};
TestHarness bisuo = new TestHarness();
long threadtime = bisuo.timetasks(100,tt);
double ans = (double)threadtime / 1000000000;
System.out.println("Thread time:" +ans + "s");
}
}
转载自原文链接, 如需删除请联系管理员。
原文链接:Java中的闭锁,转载请注明来源!