介绍
本篇文章给大家分享的是有关Java中CountDownLatch的作用有哪些,小编觉得挺实用的,因此分享给大家学习,希望大家阅读完这篇文章后可以有所收获,话不多说,跟着小编一起来看看吧。
package com.github.gleans; import java.util.concurrent.CountDownLatch; public class  TestCountDownLatch { public 才能;static  void main (String [], args), throws InterruptedException { ,,,CountDownLatch latch =, new CountDownLatch (3); ,,,new KeyPass (1000 l,,“thin  jack",,门闩).start (); ,,,new KeyPass (2000 l,,“noral  jack",,门闩).start (); ,,,new KeyPass (3000 l,,“fat  jack",,门闩).start (); ,,,latch.await (); ,,,System.out.println(“此处对数据库进行最后的插入操作~“); ,,} static 才能class KeyPass  extends Thread { ,,,private long ; ,,,private CountDownLatch countDownLatch; ,,,public KeyPass (long ,, String 名字,,CountDownLatch countDownLatch), { ,,,,,超级(名称); ,,,,,this.times =,次; ,,,,,this.countDownLatch =, countDownLatch; ,,,} ,,@Override ,,,public void 运行(),{ ,,,,,try { ,,,,,,,System.out.println(“操作人:“,+,Thread.currentThread () . getname () ,,,,,,,,,,,+,“对数据库进行插入,持续时间:“,+,this.times /, 1000, +,“秒”); ,,,,,,,thread . sleep(次); ,,,,,,,countDownLatch.countDown (); ,,,,,},catch (InterruptedException e), { ,,,,,,,e.printStackTrace (); ,,,,,} ,,,} ,,} }
图解
使用等待()提前结束操作
package com.github.gleans; import java.util.concurrent.CountDownLatch; import java.util.concurrent.TimeUnit; public class  TestCountDownLatch { public 才能;static  void main (String [], args), throws InterruptedException { ,,,CountDownLatch latch =, new CountDownLatch (3); ,,,new KeyPass (2000 l,“公司一“,,门闩).start (); ,,,new KeyPass (3000 l,“公司二“,,门闩).start (); ,,,new KeyPass (5000 l,“公司三,,,门闩).start (); ,,,latch.await (2, TimeUnit.SECONDS); ,,,System.out.println(“~ ~ ~贾总PPT巡演~ ~ ~ ~“); ,,,System.out.println(“~ ~ ~ ~融资完成,撒花~ ~ ~ ~“); ,,} static 才能class KeyPass  extends Thread { ,,,private long ; ,,,private CountDownLatch countDownLatch; ,,,public KeyPass (long ,, String 名字,,CountDownLatch countDownLatch), { ,,,,,超级(名称); ,,,,,this.times =,次; ,,,,,this.countDownLatch =, countDownLatch; ,,,} ,,@Override ,,,public void 运行(),{ ,,,,,try { ,,,,,,,thread . sleep(次); ,,,,,,,System.out.println(“负责人:“,+,Thread.currentThread () . getname () ,,,,,,,,,,,+,“开始工作,持续时间:“,+,this.times /, 1000, +,“秒”); ,,,,,,,countDownLatch.countDown (); ,,,,,},catch (InterruptedException e), { ,,,,,,,e.printStackTrace (); ,,,,,} ,,,} ,,} }
假设公司一,公司二,公司三各需要2 s, 3 s, 5 s来完成工作,贾总等不了,只能等2 s,那么就设置等待的超时时间
latch.await (2, TimeUnit.SECONDS);
以上就是java中CountDownLatch的作用有哪些,小编相信有部分知识点可能是我们日常工作会见到或用到的。希望你能通过这篇文章学到更多知识。更多详情敬请关注行业资讯频道。