dus*_*kin 1 java multithreading
我试图按照这个例子来理解join()方法:
class PrintDemo {
public void printCount() {
try {
for(int i = 5; i > 0; i--) {
System.out.println("Counter --- " + i );
}
} catch (Exception e) {
System.out.println("Thread interrupted.");
}
}
}
class ThreadDemo extends Thread {
private Thread t;
private String threadName;
PrintDemo PD;
ThreadDemo(String name, PrintDemo pd) {
threadName = name;
PD = pd;
}
public void run() {
synchronized(PD) {
PD.printCount();
}
System.out.println("Thread " + threadName + " exiting.");
}
public void start () {
System.out.println("Starting " + threadName );
if (t == null) {
t = new Thread (this, threadName);
t.start ();
}
}
}
public class TestThread {
public static void main(String args[]) {
PrintDemo PD = new PrintDemo();
ThreadDemo T1 = new ThreadDemo("Thread - 1 ", PD);
ThreadDemo T2 = new ThreadDemo("Thread - 2 ", PD);
T1.start();
T2.start();
// wait for threads to end
try {
T1.join();
T2.join();
} catch (Exception e) {
System.out.println("Interrupted");
}
}
}
Run Code Online (Sandbox Code Playgroud)
据我所知,T1.join()使主线程等待T1完成以继续其流程.我在这里纠正吗?
所以,我修改了这样的代码:
System.out.println("1");
T1.start();
System.out.println("2");
T2.start();
// wait for threads to end
try {
System.out.println("3");
T1.join();
System.out.println("4");
T2.join();
System.out.println("5");
} catch (Exception e) {
System.out.println("Interrupted");
}
Run Code Online (Sandbox Code Playgroud)
为了尝试并遵循完整的流程.
这就是我每次都得到的:
1
Starting Thread - 1
2
Starting Thread - 2
3
4
5
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 1 exiting.
Counter --- 5
Counter --- 4
Counter --- 3
Counter --- 2
Counter --- 1
Thread Thread - 2 exiting.
Run Code Online (Sandbox Code Playgroud)
而且我无法解释它......
为什么计数器打印在"5"字符后打印?我可能不太了解加入问题......