首页 > 编程知识 正文

java中死锁的几个必要条件,java闭锁原理

时间:2023-05-06 07:58:10 阅读:214393 作者:3024

闭锁 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"); }}

版权声明:该文观点仅代表作者本人。处理文章:请发送邮件至 三1五14八八95#扣扣.com 举报,一经查实,本站将立刻删除。