CountDownLatch的使用





原文路径:http://www.360doc.com/content/12/1009/16/59141_240454705.shtml

Worker类(单独的线程):

package cn.edu.bupt.thread.threadnotify;

import java.util.Random;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

public class Worker implements Runnable
{
    private CountDownLatch downLatch;
    private String name;

    public Worker(CountDownLatch downLatch, String name)
    {
        this.downLatch = downLatch;
        this.name = name;
    }

    @Override
    public void run()
    {
        this.doWork();
        try
        {
            TimeUnit.SECONDS.sleep(new Random().nextInt(10));
        }
        catch (InterruptedException ie)
        {
        }
        System.out.println(this.name + "活干完了!");
        this.downLatch.countDown();

    }

    private void doWork()
    {
        System.out.println(this.name + "正在干活...");
    }

}
 

 

 Boss类(单独的线程):

package cn.edu.bupt.thread.threadnotify;public class Boss implements Runnable
{
   
private

downLatch;
    }
    @Override
   public void run()
    {
        System.out.println(
“老板正在等所有的工人干完活……”);
       
try
        {
           
this.downLatch.await();
        }
       
catch (InterruptedException e)
        {
        }
        System.out.println(
“工人活都干完了,老板开始检查了!”

);
    }
}

 

 
CountDownLatch downLatch;
   public Boss(CountDownLatch downLatch)
    {
       
this.downLatch =

import

java.util.concurrent.CountDownLatch;

Main:

package cn.edu.bupt.thread.threadnotify;public class CountDownLatchDemo
{
   
public static void main(String[] args)
    {
        ExecutorService executor
=
 

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;import

java.util.concurrent.Executors;
Executors.newCachedThreadPool();
        CountDownLatch latch= new CountDownLatch(3);
   
        Worker w1
= new Worker(latch, “张三”);
        Worker w2
= new Worker(latch, “李四”);
        Worker w3
= new Worker(latch, “王二”);
   
        Boss boss
= new Boss(latch);
       
        executor.execute(boss);
        executor.execute(w3);
        executor.execute(w2);
        executor.execute(w1);
       
        executor.shutdown();
    }
   
}



Related posts

coded by nessus
分享:  DeliciousGReader鲜果豆瓣CSDN网摘
Trackback

only 1 comment untill now

  1. sorrel@suspended.shouts” rel=”nofollow”>.…

    ñïñ….

Add your comment now

无觅相关文章插件