高并发编程:5、Join方法介绍和经典案例

一、概述

  • join的作用,让父线程等待子线程结束之后才能继续运行 ,join的兄弟线程依然是并行执行。
  • 案列:健康信息检查:已收集3台集服务器信息,并记录第一台开始收集时间和最后一台结束收集时间。

二、代码

1、不使用join

package com.cfl.thread;

import sun.util.logging.resources.logging;

/**
 * Join 让父线程等待子线程结束之后才能继续运行
 * 健康信息检查:已收集5台集服务器信息,并记录第一台开始收集时间和最后一台结束收集时间
 * @author chenfenli
 *
 */
public class Thread5 {
    public static void main(String[] args) throws Exception {
	long startTime = System.currentTimeMillis();
	
	Thread thread1 = new Thread(new HealthCollect("M1", 10000L));
	Thread thread2 = new Thread(new HealthCollect("M2", 2000L));
	Thread thread3 = new Thread(new HealthCollect("M3", 3000L));
	
	thread1.start();
	thread2.start();
	thread3.start();
	
//	thread1.join();
//	thread1.join();
//	thread1.join();
		
	long endTime = System.currentTimeMillis();
	
	System.out.println(endTime-startTime);
	System.out.println(Thread.currentThread().getName());
    }

    public static class HealthCollect implements Runnable{
	// 模拟计算机名称
	private String machineName;
	// 模拟收集时间
	private long spendTime;
	
	private HealthCollect(String machineName, long spendTime) {
	    this.machineName = machineName;
	    this.spendTime = spendTime;
	}
	public void run() {
	    try {
		Thread.sleep(spendTime);
		System.out.println(machineName + " successfully");
	    } catch (InterruptedException e) {
		e.printStackTrace();
	    }
	}
    }
}

 

startTime: 1562513784764 endTime: 1562513784768 时间差: 4
main
M2 successfully
M3 successfully
M1 successfully
  • 可以看到M1、M2、M3还没执行完成,main方法就执行完了,计算时间也不对,无法完成案列需求。

2、打开注释,使用join

	thread1.join();
	thread1.join();
	thread1.join();
M2 successfully
M3 successfully
M1 successfully
startTime: 1562513984607 endTime: 1562513994611 时间差: 10004
main
  • 可以看到只有当M1、M2、M3都执行完成之后,main方法才执行完成,并且正确的记录了开始时间和结束时间。join的兄弟线程依然是并行执行。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值