我在 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) {}
}
}
}
关于java - 如何在另一个线程仍在运行时停止主线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23240643/