码迷,mamicode.com
首页 > 编程语言 > 详细

java_线程-锁

时间:2015-08-29 22:54:54      阅读:147      评论:0      收藏:0      [点我收藏+]

标签:

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();
        }
    }

}

 

java_线程-锁

标签:

原文地址:http://www.cnblogs.com/MarchThree/p/4769858.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!