![](/img/trans.png)
[英]What is this design (or anti-) pattern and more importantly is there a better way?
[英]What's going on in this program, and, more importantly, why?
請幫助我了解該程序的執行情況,從廣義上講,哪些概念適用於此? 解釋線程/堆棧的創建和銷毀的圖示可能會有所幫助。
class Joining {
static Thread createThread(final int i, final Thread t1) {
Thread t2 = new Thread() {
public void run() {
System.out.println(i+1);
try {
t1.join();
} catch (InterruptedException ie) {
}
System.out.println(i+2);
}
};
System.out.println(i+3);
t2.start(); //1
System.out.println(i+4);
return t2;
}
public static void main(String[] args) {
createThread(10, createThread(20, Thread.currentThread()));
}
}
添加一些調試輸出可能會幫助您理解執行:
import static java.lang.Thread.currentThread;
class Joining {
static int count = 0;
static Thread createThread(final int i, final Thread t1) {
System.out.println("Create thread with " + i + " and " + t1.getName());
Thread t2 = new Thread("Thread " + count++) {
public void run() {
System.out.println(currentThread().getName() + ": " + (i+1));
try {
System.out.println(currentThread().getName() + ": join with " + t1.getName());
t1.join();
} catch (InterruptedException ie) {
}
System.out.println(currentThread().getName() + ": " + (i+2));
}
};
System.out.println(currentThread().getName() + ": " + (i+3));
System.out.println(currentThread().getName() + ": starting thread " + t2.getName());
t2.start(); //1
System.out.println(currentThread().getName() + ": " + (i+4));
return t2;
}
public static void main(String[] args) throws InterruptedException {
Thread someThread = createThread(20, currentThread());
System.out.println("After first createThread.");
Thread.sleep(1000);
createThread(10, someThread);
}
}
輸出是
Create thread with 20 and main
main: 23
main: starting thread Thread 0
main: 24
After first createThread.
Thread 0: 21
Thread 0: join with main
Create thread with 10 and Thread 0
main: 13
main: starting thread Thread 1
main: 14
Thread 1: 11
Thread 1: join with Thread 0
Thread 0: 22
Thread 1: 12
嗯...對我來說好像t1.join
會永遠掛在第一個createThread(20,Thread.currentThread))調用上。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.