Java骚操作之CountDownLatch代码详解

网友投稿 268 2023-01-31

Java骚操作之CountDownLatch代码详解

简述

用来干嘛的?当你在方法中调用了多个线程,对数据库进行了一些不为人知的操作后,还有一个操作需要留到前者都执行完的重头戏,就需要用到 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(1000L, "thin jack", latch).start();

new KeyPass(2000L, "noral jack", latch).start();

new KeyPass(3000L, "fat jack", latch).start();

latch.await();

System.out.println("此处对数据库进行最后的插入操作~");

}

static class KeyPass extends Threahttp://d {

private long times;

private CountDownLatch countDownLatch;

public KeyPass(long times, String name, CountDownLatch countDownLatch) {

super(name);

this.times = times;

this.countDownLatch = countDownLatch;

}

@Override

public void run() {

try {

System.out.println("操作人:" + Thread.currentThread().getName()

+ "对数据库进行插入,持续时间:" + this.times / 1000 + "秒");

Thread.sleep(times);

countDownLatch.countDown();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

图解

使用await()提前结束操作

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(2000L, "公司一", latch).start();

new KeyPass(3000L, "公司二", latch).start();

new KeyPass(5000L, "公司三", latch).start();

latch.await(2, TimeUnit.SECONDS);

System.out.println("~~~贾总PPT巡演~~~~");

System.out.println("~~~~融资完成,撒花~~~~");

}

static class KeyPass extends Thread {

private long times;

private CountDownLatch countDownLatch;

public KeyPass(long times, String name, CountDownLatch countDownLatch) {

super(name);

this.times = times;

this.countDownLatch = countDownLatch;

}

@Override

public void run() {

try {

Thread.sleep(times);

System.out.println("负责人:" + Thread.currentThread().getName()

+ "开始工作,持续时间:" + this.times / 1000 + "秒");

countDownLatch.countDown();

} catch (InterruptedException e) {

e.printStackTrace();

}

}

}

}

假设公司一、公司二、公司三各需要2s、3s、5s来完成工作,贾总等不了,只能等2s,那么就设置await的超时时间

latch.await(2, TimeUnit.SECONDS);

执行结果

负责人:公司一开始工作,持续时间:2秒

~~~贾总PPT巡演~~~~

~~~~融资完成,撒花~~~~

负责人:公司二开始工作,持续时间:3秒

负责人:公司三开始工作,持续时间:5秒

方法描述

总结

这个操作可以说是简单好用,目前还未遇见副作用,若是有大佬,可以告知弟弟一下,提前表示感谢~

版权声明:本文内容由网络用户投稿,版权归原作者所有,本站不拥有其著作权,亦不承担相应法律责任。如果您发现本站中有涉嫌抄袭或描述失实的内容,请联系我们jiasou666@gmail.com 处理,核实后本网站将在24小时内删除侵权内容。

上一篇:windows7配置java环境变量的图文教程
下一篇:详解查看JAVA API及JAVA源码的方法
相关文章

 发表评论

暂时没有评论,来抢沙发吧~