• java_线程-锁


    package com.demo.test3;
    
    import java.util.concurrent.CountDownLatch;
    
    /**
     * @author QQ: 1236897
     *
     */
    //闭锁
    //nThread - 线程数目
    //startGate -确保所有线程就绪-》countDown->所有线程工作
    //endGate - 等待所有线程完成工作后才返回timeTask方法
    public class CountDownLockTest {
    
        /**
         * @param args
         */
        public static void main(String[] args) {
            // TODO Auto-generated method stub
            Caller caller = new Caller();
            MyTask task = new MyTask();
    
            try {
                System.out.println(caller.timeTask(5, task));
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }
    
    }
    
    class Caller {
    
        public long timeTask(int nThreads, final Runnable task)
                throws InterruptedException {
    
            final CountDownLatch startGate = new CountDownLatch(1);
            final CountDownLatch endGate = new CountDownLatch(nThreads);
    
            for (int i = 0; i < nThreads; i++) {
                Thread t = new Thread() {
    
                    public void run() {
                        try {
                            System.out.println("startGate await");
                            startGate.await();
                            try {
                                task.run();
                            } finally {
                                endGate.countDown();
                            }
    
                        } catch (InterruptedException e) {
                        }
                    }
    
                };
    
                t.start();
            }
    
            long start = System.nanoTime();
            System.out.println("startGate countDown");
            startGate.countDown();
            endGate.await();
            long end = System.nanoTime();
            System.out.println("return");
            return end - start;
        }
    
    }
    
    class MyTask implements Runnable {
    
        /*
         * (non-Javadoc)
         * 
         * @see java.lang.Runnable#run()
         */
        @Override
        public void run() {
            // TODO Auto-generated method stub
            System.out.println("id sleep: - " + Thread.currentThread().getId());
            try {
                Thread.sleep(5000);
                System.out.println("Sleep done: - "
                        + Thread.currentThread().getId());
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                Thread.currentThread().interrupt();
            }
        }
    
    }
  • 相关阅读:
    Arduino
    DTU
    现代信号处理与应用
    matlab学习记录
    列车准点节能操纵
    泊松过程
    序号生成算法odoo
    操作系统特性
    c语言中的变量
    xml中的四则运算与时间爱格式
  • 原文地址:https://www.cnblogs.com/MarchThree/p/4769858.html
Copyright © 2020-2023  润新知