![](/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.