![](/img/trans.png)
[英]How to use a thread to run another JFrame while the main is still running
[英]how to stop main thread while another thread still running
我在main方法中啟動了t1線程,並想停止主線程,但我的t1線程仍在運行。 有可能的? 怎么樣?
public static void main(String[] args)
{
Thread t1=new Thread()
{
public void run()
{
while(true)
{
try
{
Thread.sleep(2000);
System.out.println("thread 1");
}
catch(Exception e)
{}
}
}
};
t1.start();
}
當Java程序啟動時,一個線程立即開始運行。 通常將其稱為程序的主線程,因為它是程序啟動時執行的線程。 主線程很重要,原因有兩個:
•它是從中產生其他“ 子 ”線程的線程。
•它必須是完成執行的最后一個線程。 當主線程停止時,您的程序終止。
還有一件事,當所有非守護程序線程死亡時,程序終止(守護程序線程是標有setDaemon(true)的線程)。
這是一個簡單的小代碼段,以說明區別。 嘗試使用setDaemon中true和false的每個值。
public class DaemonTest {
public static void main(String[] args) {
new WorkerThread().start();
try {
Thread.sleep(7500);
} catch (InterruptedException e) {}
System.out.println("Main Thread ending") ;
}
}
public class WorkerThread extends Thread {
public WorkerThread() {
setDaemon(false) ; // When false, (i.e. when it's a user thread),
// the Worker thread continues to run.
// When true, (i.e. when it's a daemon thread),
// the Worker thread terminates when the main
// thread terminates.
}
public void run() {
int count=0 ;
while (true) {
System.out.println("Hello from Worker "+count++) ;
try {
sleep(5000);
} catch (InterruptedException e) {}
}
}
}
常規線程可以防止VM正常終止(即,通過到達main方法的末尾-您未在示例中使用System#exit(),這將根據文檔終止VM)。
為了使線程不阻止常規VM終止,必須在啟動線程之前通過Thread#setDaemon(boolean)將其聲明為守護程序線程。
在您的示例中-主線程在到達代碼末尾時(在t1.start();之后)死亡,而VM-包括t1-在t1到達其代碼末尾(在while(true)之后)死亡從不或異常終止時。)
將這個問題 ,這個答案與另一個類似的問題和文檔進行比較 。
System.exit(0)
退出當前程序。
“ Thread.join()
”方法可以幫助您實現所需的目標。
任何其他線程正在運行時,您無法停止主線程。 (所有子線程都從主線程中產生。)您可以使用Thread.join()函數使主線程在其他線程執行時保持等待狀態。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.