您的位置:首页 > 编程语言 > Java开发

Java多线程的join方法

2017-03-15 15:29 337 查看
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的意思!
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: