线程的join()方法

之前我的线程两篇文章用了join()而没有详细说明有什么用~今天就来说下join()的作用。

join()就是使异步执行的线程变成同步执行。也就是说,当调用线程实例start()后这个方法立即返回。如果在调用start()后需要使用一个由这个线程计算得到的值,就必须使用join()方法。使用join()才能保证start()方法后面的某条语句在线程执行后执行。

下面代码演示:

public class ThreadJoin extends Thread{
	public static int num = 0;
	
	public static synchronized void numAdd(){
		num++;
	}
	@Override
	public void run() {
		for (int i = 0; i <10; i++) {
			numAdd();
			try {
				sleep(3);//为了准确性
			} catch (InterruptedException e) {
				System.out.println(e.getMessage());
			}
		}
	}
	public static void main(String[] args) throws InterruptedException {
				Thread threads[] = new Thread[100];
				for(int i = 0;i<threads.length;i++){
					threads[i] = new ThreadJoin();
				}
				for(int i = 0;i<threads.length;i++){
					threads[i].start();
			}
					for(int i = 0;i<threads.length;i++){
						threads[i].join();
				}
					System.out.println("n="+ThreadJoin.num);
			}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值