zoukankan      html  css  js  c++  java
  • CountDownLatch 部分加载和同时并发业务。

    按顺序部分加载:

    import java.util.concurrent.CountDownLatch;
    
    /**
     * @Title: ThreadCountDownTest.java
     * @Description:
     * @author: wuwenjie
     * @date: 2019.07.17 16:43
     * 
     */
    public class ThreadCountDownTest {
    
        public static void main(String[] args) {
    // 初始化闭锁,并设置资源个数
            CountDownLatch latch = new CountDownLatch(2);
    
            Thread t1 =new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(1000);
                //加载1 latch.countDown(); System.out.println(
    111); } catch (InterruptedException e) { e.printStackTrace(); } } });
    Thread t2
    = new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(12000);
                //加载2 latch.countDown(); System.out.println(
    222); } catch (InterruptedException e) { e.printStackTrace(); } } }); Thread t3 = new Thread(new Runnable() { @Override public void run() { try {
                 latch.await();
                 //加载完成业务使用 System.out.println(
    333); } catch (InterruptedException e) { e.printStackTrace(); } } }); t1.start(); t2.start(); t3.start(); } }

    2.同时业务并发处

    import java.util.concurrent.CountDownLatch;
    
    public class ThreadCountDownTest {
    
        public static void main(String[] args) {
    // 初始化闭锁,并设置资源个数
            CountDownLatch latch = new CountDownLatch(2);
    
            Thread t1 =new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(1000);
                        latch.countDown();
                //等待所有执行完,并发 latch.await();
    System.out.println(
    111); } catch (InterruptedException e) { e.printStackTrace(); } } }); Thread t2 = new Thread(new Runnable() { @Override public void run() { try { Thread.sleep(12000); latch.countDown(); latch.await(); System.out.println(222); } catch (InterruptedException e) { e.printStackTrace(); } } }); Thread t3 = new Thread(new Runnable() { @Override public void run() { try { latch.await(); System.out.println(333); } catch (InterruptedException e) { e.printStackTrace(); } } }); t1.start(); t2.start(); t3.start(); } }
  • 相关阅读:
    紫书 例题 9-2 UVa 437 ( DAG的动态规划)
    紫书 例题 9-1 UVa 1025 ( DAG的动态规划)
    紫书 习题 10-44 UVa 11246 ( 容斥原理)
    2018 NOIP备战计划
    紫书 习题 10-32 UVa 1414 ( 迷之规律)
    HBase简介(很好的梳理资料)
    几种必知的oracle结构图
    hadoop之eclipse环境的配置
    ant&mvn的使用总结
    hadoop2.2.0安装
  • 原文地址:https://www.cnblogs.com/jay-wu/p/11244438.html
Copyright © 2011-2022 走看看