Java多线程的join方法

join方法:

例如我们有耗时操作需要在子线程完成的话,然后需要早主线程获取结果的话,我们可以如下实现:

package com.daxin;

class JoinThread extends Thread {

	private int count = 0;

	public int getCount() {
		return count;
	}

	public void setCount(int count) {
		this.count = count;
	}

	@Override
	public void run() {

		try {
			Thread.sleep(5000);

			for (int i = 0; i < 6; i++) {
				count++;
			}

			System.out.println("子线程count运行完毕,count =" + count);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}

public class JoinDemo {

	public static void main(String[] args) throws Exception {
		JoinThread jt = new JoinThread();
		jt.start();
		
		System.out.println(jt.getCount());

	}

}
但是实际上输出的是:0,这是因为子线程没有执行完毕,所以导致主线程获取的结果不正确。那么如何实现这个呢 ?

其实可以使用Callable接口实现异步获取结果,但是我们也可以使用Thread实现,那么就需要使用join方法:


package com.daxin;

class JoinThread extends Thread {

	private int count = 0;

	public int getCount() {
		return count;
	}

	public void setCount(int count) {
		this.count = count;
	}

	@Override
	public void run() {

		try {
			Thread.sleep(5000);

			for (int i = 0; i < 6; i++) {
				count++;
			}

			System.out.println("子线程count运行完毕,count =" + count);
		} catch (InterruptedException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}

}

public class JoinDemo {

	public static void main(String[] args) throws Exception {
		JoinThread jt = new JoinThread();
		jt.start();
		
		jt.join();
		System.out.println(jt.getCount());

	}

}

这次输出:6 正确。join的方法作用就是等待子线程完毕之后,加入主线程一起向下执行。也正符合join的意思!








评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值