zoukankan      html  css  js  c++  java
  • java 中的CountDownLatch

    直接使用thread可以使用thread和wait notify 实现顺序执行

    线程池中可以使用CountDownLatch 进行顺序执行

    package com.test;
    
    import java.util.concurrent.CountDownLatch;
    
    public class Sample {
        /**
         * 计数器,用来控制线程
         * 传入参数2,表示计数器计数为2
         */
        private final static CountDownLatch mCountDownLatch = new CountDownLatch(2);
    
        /**
         * 示例工作线程类
         */
        private static class WorkingThread extends Thread {
            private final String mThreadName;
            private final int mSleepTime;
            public WorkingThread(String name, int sleepTime) {
                mThreadName = name;
                mSleepTime = sleepTime;
            }
    
            @Override
            public void run() {
                System.out.println("[" + mThreadName + "] started!");
                try {
                    Thread.sleep(mSleepTime);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                mCountDownLatch.countDown();
                System.out.println("[" + mThreadName + "] end!");
            }
        }
    
        /**
         * 示例线程类
         */
        private static class SampleThread extends Thread {
    
            @Override
            public void run() {
                System.out.println("[SampleThread] started!");
                try {
                    // 会阻塞在这里等待 mCountDownLatch 里的count变为0;
                    // 也就是等待另外的WorkingThread调用countDown()
                    mCountDownLatch.await();
                } catch (InterruptedException e) {
    
                }
                System.out.println("[SampleThread] end!");
            }
        }
    
        public static void main(String[] args) throws Exception {
            // 最先run SampleThread
            new SampleThread().start();
            // 运行两个工作线程
            // 工作线程1运行5秒
            new WorkingThread("WorkingThread1", 5000).start();
            // 工作线程2运行2秒
            new WorkingThread("WorkingThread2", 2000).start();
        }
    }

    转自 https://www.cnblogs.com/flyme/p/4568063.html

  • 相关阅读:
    Python3 基本数据类型
    C语言使用以及其它语言经常出的错误
    Deleting array elements in JavaScript
    postgresql 导出建表语句的方法-类似describe table
    什么是分布式系统(通俗易懂的说法)
    什么是分布式系统,分布式系统例子?
    【转】Linux cp -a用法
    [转]Go基础之锁的初识
    fabricJs使用系列(一)
    chrome 的onbeforeunload事件没有触发
  • 原文地址:https://www.cnblogs.com/tiancai/p/8268332.html
Copyright © 2011-2022 走看看