一个多线程例子,使用CountDownLatch

来源:互联网 发布:spark mac 安装 编辑:程序博客网 时间:2024/05/16 14:21
package com.test;import java.util.Date;import java.util.concurrent.CountDownLatch;public class TaskTool {    /**     * 主程序     *      * @param args     */    public static void main(String[] args) {        // TODO Auto-generated method stub        // 执行函数        ExecFunc();    }    /*     * 需要执行的函数     */    private static void ExecFunc() {        try {            debug("主线程开始时间 = " + new Date());            // 主线程睡眠2秒种,防止CPU资源被耗尽            Thread.sleep(2000);            int countDown = 1000;// 初始化countDown,几行数据就代表有几个线程            CountDownLatch threadsignalCountDownLatch = new CountDownLatch(countDown);            for (int i = 0; i < countDown; i++) {                // 执行线程                TimeingThread timeingThread = new TimeingThread(threadsignalCountDownLatch);                // 线程加入等待                timeingThread.start();            }            // 等待子线程结束,开始主线程            threadsignalCountDownLatch.await();            debug("主线程结束时间 = " + new Date());        } catch (Exception e) {            debug("系统异常 = " + e.getMessage());        }    }    /**     * 定制执行的内部类     *      * @author admin     *     */    private static class TimeingThread extends Thread {        // 线程计数器        private CountDownLatch threadsSignal;        // 构造方法        public TimeingThread(CountDownLatch threadsSignal) {            this.threadsSignal = threadsSignal;        }        // 执行线程        public void run() {            StartFuncJob();            threadsSignal.countDown();        }        /**         * 开始执行定时任务         */        private void StartFuncJob() {            try {                for (int i = 0; i < 3; i++) {                    debug(Thread.currentThread().getName() + " ------------数数 ==" + i);                    Thread.sleep(1000);                }                debug(Thread.currentThread().getName() + " ------------数完了-----------------------------------------");            } catch (Exception ex) {            } finally {                // 计数器减少1                threadsSignal.countDown();            }        }    }    public static void debug(Object obj) {        System.out.println(obj);    }    public static void debug() {        System.out.println();    }}