[英]Threads in Java,can the stack with main() die/end before the stack with run()?
如果我要編寫一個創建線程的主類,則該類創建的線程是否有可能超過創建它的類的main()。
在某種程度上,這似乎是可能的,因為我可以使新創建的線程休眠一個小時,從而使新堆棧進入阻塞狀態,從而使原始主堆棧可以自由執行,該主堆棧可以執行,而無需執行任何其他操作,而新堆棧仍處於阻塞狀態。
但是另一方面,在Java中有一條聲明,即一切都以main()方法開始和結束。
請讓我知道哪一個是正確的
是的,但前提是您創建的線程不是守護程序線程。 該(非守護程序)實際上是默認設置。
Java中有這樣一條語句:一切都以main()方法開始和結束。
這不是真的。 你有
import java.io.PrintStream;
class Main {
static {
System.out.println("0) Printed before main");
}
public static void main(String... args) {
System.out.println("1) Printed in main");
Runtime.getRuntime().addShutdownHook(new Thread() {
public void run() {
System.out.println("3) Printed long after main");
}
});
throw new RuntimeException() {
public void printStackTrace(PrintStream ps) {
System.err.println();
System.out.println("2) Printed after main");
}
};
}
}
版畫
Exception in thread "main"
0) Printed before main
1) Printed in main
2) Printed after main
3) Printed long after main
這不僅是可能的,而且是編寫Swing應用程序時的正常狀態。 您不應該在Swing線程之外創建Swing組件,因此主線程將任務排隊,以在Swing線程中創建UI,然后退出。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.