线程等待:
等待线程死亡
- 当前线程:代码执行的时候,所在的线程
- t 线程:线程引用对象
- 当前线程进行阻塞(运行态–>阻塞态)等待(满足一定条件),t线程(不做任何处理,让t执行运行)
- 条件:(哪个条件先执行完,先满足)
a.传入时间(时间值+时间单位毫秒)
b.线程引用对象执行完毕
public static void without() throws InterruptedException {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
});
t.start();
t.join();
System.out.println(Thread.currentThread().getName());
}
public static void withoutSleep() throws InterruptedException {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName());
}
});
t.start();
t.join(2000);
System.out.println(Thread.currentThread().getName());
}
public static void withSleep() throws InterruptedException {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(3000);
System.out.println("Thread baby");
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t.start();
t.join(2000);
System.out.println("main");
}
守护线程
public static void DaemonTest() {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(99999999999L);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}, "FirstTest");
t.setDaemon(true);
t.start();
}