为什么打印此代码:内线程1内线程2并进入类似无限循环的东西,因为它没有终止。
class Thread2 extends Thread{
public void run(){
try {
Thread1 t = new Thread1();
Thread.sleep(2000);
System.out.println("Inside Thread2");
}
catch(InterruptedException e){
System.out.println("Exception occurred inside Thread2");
}
}
}
class Thread1 extends Thread{
public void run(){
Thread2 t = new Thread2();
t.setDaemon(true);
t.start();
try {
Thread.sleep(1000);
System.out.println("Inside Thread1");
}
catch(InterruptedException e){
System.out.println("Exception occurred inside Thread1");
}
Thread t2 = Thread.currentThread();
try{
t2.join();
}
catch(InterruptedException e){
System.out.println(e);
}
}
}
public class DaemonThread {
public static void main(String[] args) {
Thread1 t = new Thread1();
t.start();
}
}
我不明白加入是怎么回事
我无法理解join是如何工作的。
这真的很简单。t. join()
什么都不做。它一直什么都不做,直到线程t
完成,然后它返回。这就是它的全部。
您也可以将t. join()
视为类似于Thread.睡眠(n)
,除了它不是Hibernate到n
毫秒过去,而是Hibernate到线程t
完成。
附言,你写了这个:
Thread t2 = Thread.currentThread();
try{
t2.join();
}
catch(InterruptedException e){
System.out.println(e);
}
这将永远Hibernate。Thread.当前线程()
有一个误导性的名称。它应该被称为Thread. caller()
或Thread.self()
或Thread.me()
。它返回调用它的线程的Thread
实例。
当你写t2. join()
时,你是说,等到t2
完成,但是t2
是调用t2.join()
的线程。join()
调用直到线程完成才会返回,但是线程直到join()
调用返回才能完成。有些人称之为自死锁。
你说得对,这段代码会进入无限循环,我看到几个原因
-主线程创建并启动一个Thread1对象,它是一个用户线程。
如果你想解决这个问题,你可以尝试从Thread1类中删除join()调用。这样,主线程就不会等待自己,而是完成执行。然后JVM将退出并终止所有守护线程。另一个可能的解决方案是将Thread1类也设为守护线程,这样当main方法结束时就没有用户线程了。然后JVM将退出并终止所有守护线程。