thread-join

package com.citi.icg.ddi.client.service.test;

import java.util.ArrayList;
import java.util.List;

public class ThreadTest {

    /**
     * @param args
     */
    public static void main(String[] args) {

        List<SubThread> threads = new ArrayList<SubThread>();
        for (int i = 0; i < 10; i++) {
            SubThread thread = new SubThread(i);
            threads.add(thread);
            thread.start();
        }

        // 主線程處理其他工作,讓子線程異步去執行.
        mainThreadOtherWork();
        System.out.println("now waiting sub thread done.");
        // 主線程其他工作完畢,等待子線程的結束, 調用join系列的方法即可(可以設置超時時間)
        try {

            for (Thread t : threads) {
                t.join();// main 線程掛起直到目標線程t結束才恢復(thread.isAlive() return false)
            }

        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("now all done.");

    }

    private static void mainThreadOtherWork() {
        System.out.println("main thread work start");
        try {
            Thread.sleep(3000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("main thread work done.");
    }

    public static class SubThread extends Thread {
        int i;

        public SubThread(int i) {
            this.i = i;
            this.setName("Thread" + i);
        }

        @Override
        public void run() {
            working();
        }

        private void working() {
            System.out.println(i + "sub thread start working.");
            busy();
            System.out.println(i + "sub thread stop working.");
        }

        private void busy() {
            try {
                sleep(5000L);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }

    }

}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章