怎么知道java多线程已经运行结束

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

东西贴到这里是因为360DOC屏蔽直接从页面复制内容,这种没意思的做法很是烦人,虽然我另存一下页面,在本地重新打开就可以复制了,但是还是不如让大家一步到位,直接复制多好。

worker:

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

    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:

import java.util.concurrent.CountDownLatch;

public class Boss implements Runnable
{
    private CountDownLatch downLatch;

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

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

}

main:

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

public class CountDownLatchDemo
{
    public static void main(String[] args)
    {
        ExecutorService executor = 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();
    }
    
}


你可能感兴趣的:(java,多线程)