我正在尝试学习有关Java线程的知识。我没有为t1.t2线程设置isDeamon(true),但主线程仍在等待。所以我不知道该怎么解释。 THX,请给我一些帮助。
有我的代码:
package runnable;
public class RunnableTest1 {
public static int flag = 0;
public static void main(String[] args){
Thread t1 = new Thread(new NewMyRunnable1("t1"));
t1.setName("My Test 1");
System.out.println(t1.toString()+t1.isDaemon());
Thread t2 = new Thread(new NewMyRunnable1("t2"));
t2.setName("My Test 2");
System.out.println(t2.toString()+t2.isDaemon());
t1.start();
t2.start();
System.out.println("main done "+flag);
}
}
class NewMyRunnable1 implements Runnable {
private String name = "";
public static int TIMES = 10;
public NewMyRunnable1(String name) {
this.name = name;
}
@Override
public void run() {
int i = 0;
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
while(i < TIMES){
System.out.println(name +": "+ i);
Thread.yield();
i++;
}
}
}
最佳答案
您有两个线程,这些线程不是恶魔。您的主线程无法在两个线程都完成之前完成,因为两个线程都不是恶魔。这是正确的行为。
您可以将两个线程都设置为.setDemon(true);
并运行您的程序,它无需等待t1和t2就可以完成。
见点2
关于java - 主线程等待isDeamon()设置为false end的所有线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66049125/