多线程学习笔记六-Thread的join方法

在A线程中调用了B线程的join()方法时,表示只有当B线程执行完毕时,A线程才能继续执行。

public class ThreadJoin {
    public static void main(String[] args) {
        Thread t1 = new Thread(()->{
            IntStream.range(1,1000).forEach(i-> System.out.println(Thread.currentThread().getName()));
        });
        Thread t2 = new Thread(()->{
            IntStream.range(1,1000).forEach(i-> System.out.println(Thread.currentThread().getName()));
        });
        t1.start();
        t2.start();
        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        Optional.of("All of task finish done").ifPresent(System.out::println);
        IntStream.range(1,1000).forEach(i-> System.out.println(Thread.currentThread().getName()));
    }
}

总结:
main线程会等到t1和t2线程执行完毕之后,才进行打印

public class ThreadJoin2 {
    public static void main(String[] args) {
        long startTime = System.currentTimeMillis();
        Thread m1 = new Thread(new CaptureRunnable("m1", 10000L));
        Thread m2 = new Thread(new CaptureRunnable("m2", 30000L));
        Thread m3 = new Thread(new CaptureRunnable("m3", 15000L));

        m1.start();
        m2.start();
        m3.start();

        try {
            m1.join();
            m2.join();
            m3.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        long endTime = System.currentTimeMillis();

        System.out.println("save data start time is="+startTime+",endtime is="+endTime);
    }
}
class CaptureRunnable implements Runnable{
    private String machineName;

    private long spendTime;

    public CaptureRunnable(String machineName, long spendTime) {
        this.machineName = machineName;
        this.spendTime = spendTime;
    }

    @Override
    public void run() {
        try {
            Thread.sleep(spendTime);
            System.out.println(machineName+" completed data capture and successful spend time is" + spendTime);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    public String getResult(){
        return machineName+ " finish";
    }
}

在这里插入图片描述

总结:三个线程同时对三台机器进行数据采集,通过join方式,让这三个线程交替运行,最后mian线程记录最后一台机器采集数据完成的时间

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值