回覆列表
  • 1 # 程式設計頌

    要實現這個情況,必須知道以下幾點

    1、java中執行緒的結束是由run方法執行完成後自動結束的

    2、在main執行緒(主執行緒)中,需要得到所有執行緒的引用。

    3、知道jdk提供的CountDownLatch的用法

    例子如下:

    public static void main(String[] args) throws InterruptedException

    {

    //CountDownLatch作為計數器紀錄有幾個執行緒,例如有2個執行緒

    CountDownLatch latch=new CountDownLatch(2);

    Worker worker1=new Worker( latch);

    Worker worker2=new Worker(latch);

    worker1.start();// 啟動執行緒

    worker2.start();//

    //等待所有工人完成工作

    latch.await();

    System.out.println("all work done at "+sdf.format(new Date()));

    }

    class Worker extends Thread

    {

    private CountDownLatch latch;

    public Worker(CountDownLatch latch)

    {

    this.latch = latch;

    }

    public void run()

    {

    xxxxx

    //在run方法結束之前,講執行緒計數器減一

    latch.countDown();

    }

    }

  • 中秋節和大豐收的關聯?
  • 現在回去玩劍網三是不是有些太晚了?