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

    }

}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值