1、首先来看段代码
public class JoinRelase {
static Object object = new Object();
public static void main(String[] args) throws InterruptedException{
for (int i=0; i<2; i++){
Thread thread = new Thread(new SubThread(), "Daemon Thread!"+i);
thread.setName("thread-" + i);
thread.start();
Thread.sleep(10000);
}
System.out.println("主线程结束");
}
static class SubThread implements Runnable{
@SneakyThrows
@Override
public void run() {
synchronized (Thread.currentThread()) {
System.out.println("获取到锁!!!ThreadName: " + Thread.currentThread().getName());
Thread.currentThread().join();
}
}
}
}
运行这段代码你会发现,线程运行如下,一直都没有停止
2、原因分析
join() 这个方法的作用是先将当前线程挂起,待其他线程结束后在执行当前线程的代码。如果调用了Thread.currentThread().join(); 这个方法,那么线程一直在阻塞,无法终止。因为它自己在等待自己结束;这无疑会造成死锁;所以千万不能用Thread.currentThread().join()。当我对上面代码进行如下改造后就可成功运行
public class JoinRelase {
static Object object = new Object();
public static void main(String[] args) throws InterruptedException{
for (int i=0; i<2; i++){
Thread thread = new Thread(new SubThread(), "Daemon Thread!"+i);
thread.setName("thread-" + i);
thread.start();
thread.join(); // 将join放在这里,让主线程来调用
Thread.sleep(10000);
}
System.out.println("主线程结束");
}
static class SubThread implements Runnable{
@SneakyThrows
@Override
public void run() {
synchronized (Thread.currentThread()) {
System.out.println("获取到锁!!!ThreadName: " + Thread.currentThread().getName());
// Thread.currentThread().join();
}
}
}