以下代码的输出为9;但我的问题是哪个线程会调用join()方法。主线程调用join方法比什么意思?所有其他线程应该等到main方法完成?然后输出不应该是9?
public class Starter extends Thread {
private int x = 2;
public static void main(String[] args) throws Exception {
new Starter().makeItSo();
}
public Starter(){
x = 5;
start();
}
public void makeItSo() throws Exception {
join();
x = x - 1;
System.out.println(x);
}
public void run() { x *= 2; }
}
答案 0 :(得分:1)
join()
中的makeItSo()
确实令人困惑。从join()
移除makeItSo()
并从start()
构造函数中删除Starter
,您的代码与此相同(忽略异常):
Starter other_thread = new Starter();
other_thread.start(); // run gets executed in other_thread
other_thread.join(); // waits for other_thread to finish running
other_thread.makeItSo();
在代码中,它是在辅助线程上调用join
的主线程。这导致主线程在计算run()
并将其打印出来之前等待x-1
的结束。
因此,辅助线程将计算x*2 -> 10
,并且由于x - 1 -> 9
,主线程计算join()
之后。
答案 1 :(得分:0)
主线程调用join方法,因此它将等待Starter生成的线程停止。当您调用新的Starter()时,它会启动一个快速完成的线程。有可能make会等到启动器结束。为了更好的测试,让睡眠运行并跟踪经过的时间。你会看到它等待Starter结束。
答案 2 :(得分:0)
public class Starter extends Thread {
private int x = 2;
public static void main(String[] args) throws Exception {
System.out.println("Start of main "+Thread.currentThread().getName());
new Starter().makeItSo();
System.out.println("End of main "+Thread.currentThread().getName());
}
public Starter(){
x = 5;
System.out.println("Before starting thread " + Thread.currentThread().getName());
start();
System.out.println("After starting thread " + Thread.currentThread().getName());
}
public void makeItSo() throws Exception {
System.out.println("Before join " + Thread.currentThread().getName());
join();
System.out.println("After join " + Thread.currentThread().getName());
x = x - 1;
System.out.println(x);
System.out.println(Thread.currentThread().getName());
}
public void run() {
System.out.println("Inside running thread "+Thread.currentThread().getName() +"with value of x:" +x);
x *= 2;
}
}
<强>输出强>
Start of main main
Before starting thread main
After starting thread main
Before join main
Inside running thread Thread-0with value of x:5
After join main
9
main
End of main main
通过代码,它几乎是自我解释。主线程是在构造函数中生成的线程0等待连接以完成的线程。主线程没有结束,直到makeItSo()
函数调用结束。