使用的场景:业务逻辑相同,处理的数据不同,需要等到子线程处理完,最后由父线程进行统计处理的结果;这里使用了join方法。

/**
 * @Author: lazy
 * @Date: 2019/11/27 9:33
 * @Version 1.0.0
 * @Description
 */
public class ThreadTest {
    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        Thread t1 = new Thread(new RunnableTest("M1",5000L ));
        Thread t2 = new Thread(new RunnableTest("M2",10000L ));
        Thread t3 = new Thread(new RunnableTest("M3",15000L ));
        t1.start();
        t2.start();
        t3.start();

        try {
            //join要在start()之后,
            // 若放在t1,t2,t3的start之后,相当于要等t1执行完,在执行t2依此类推;
            //不是交替进行的
            t2.join();
            t1.join();
            t3.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        long endTime = System.currentTimeMillis();
        System.out.println("beging save data:"+"endTime:"+endTime);
        
    }
}

class RunnableTest implements Runnable{
    private String name;//线程名称
    private long time;//使用线程睡眠方法,模拟每个线程处理的时间
    public RunnableTest(String name,long time){
        this.name = name;
        this.time = time;
    }
    @Override
    public void run() {
        try {
            Thread.sleep(time);
            System.out.println(name+" is finished" + "[" + time + "]");
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

  若是不确定创建几个时,可以使用集合的形式,如下:

/**
 * 若在不明确创建的线程具体个数,需要放入到一个集合中
 * @Author: lazy
 * @Date: 2019/11/27 9:52
 * @Version 1.0.0
 * @Description
 */
public class ThreadTest2 {
    public static void main(String[] args) {
        List<Thread> list = new ArrayList<>();
        for(int i = 0; i < 4; i++){
            String name = "M" + i;
            long time = 5000 + i*5000;
            Thread thread = new Thread(new RunnableTest(name, time));
            thread.start();
            list.add(thread);
        }
        for(Thread thread : list){
            try {
                thread.join();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        long endTime = System.currentTimeMillis();
        System.out.println("beging save data:"+"endTime:"+endTime);
    }
}

  

posted on 2019-11-27 10:59  lazyli  阅读(130)  评论(0编辑  收藏  举报