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

  • 相关阅读:
    485通讯和电力线载波通讯[收集转载]
    鹿城通综合业务系统常见问题
    485总表专题
    试试Live Writer的代码插件
    WPF路径动画——XAML篇
    无功电量的抄收
    一个JQuery操作Table的好方法
    季节计算脚本
    【学艺不精系列】关于Json.NET的反序列化
    NT6.x以上系统,多版本SQL Server局域网配置
  • 原文地址:https://www.cnblogs.com/tiancai/p/8268332.html
Copyright © 2011-2022 走看看