• 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

  • 相关阅读:
    WF编译报错
    VS2012编译错误信息,错误列表却没显示
    SQL Server带游标的SQL
    SQL Server创建LinkServer
    ASP.NET自定义控件加载资源WebResource问题
    sqlserver 增加用户并分配权限
    Java for C#程序员
    laravel安装
    Convert Geometry data into a Geography data in MS SQL Server
    linux安装ruby
  • 原文地址:https://www.cnblogs.com/tiancai/p/8268332.html
Copyright © 2020-2023  润新知