目录
1. 线程终⽌
线程的常用属性及获取方法(2)_小bit~的博客-CSDN博客
2. 线程等待 join
有时,我们需要等待⼀个线程完成它的⼯作后,才能进⾏⾃⼰的下⼀步⼯作。例如,李四只有等
张三下班了他才上班,这时我们需要⼀个⽅法明确等待线程的结束。

public class ThreadByJoin {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(() -> {
//1. 张三开始上班
System.out.println("1. 张三开始上班 :" + LocalDateTime.now());
//2. 张三正在上班
try {
Thread.sleep(10 * 1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//3. 张三下班
System.out.println("3. 张三下班: " + LocalDateTime.now());
});
// 启动程序
t1.start();
// 等待线程 t1 执行完之后,再执行后面的代码
t1.join();
t1.join(500);
Thread t2 = new Thread(() -> {
//1. 李四开始上班
System.out.println("1.李四开始上班:" + LocalDateTime.now());
// 2.李四正在上班
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
// 3.李四下班
System.out.println("3.李四下班:" + LocalDateTime.now());
});
t2.start();
}
}
输出:
1. 张三开始上班 :2022-03-28T12:20:43.495
3. 张三下班: 2022-03-28T12:20:53.497
1.李四开始上班:2022-03-28T12:20:53.498
3.李四下班:2022-03-28T12:20:54.498
3. yield 让出执⾏权
public class ThreadYield {
public static void main(String[] args) {
Thread t1 = new Thread(() -> {
Thread cThread = Thread.currentThread();
for (int i = 0; i < 5; i++) {
Thread.yield();
System.out.println("执行了线程:" + cThread.getName());
}
},"张三");
t1.start();
//创建并启动线程
new Thread(() -> {
Thread cThread = Thread.currentThread();
for (int i = 0; i < 5; i++) {
System.out.println("执行线程:" + cThread.getName());
}
},"李四").start();
}
}
输出:
执行了线程:张三
执行了线程:张三
执行了线程:张三
执行线程:李四
执行线程:李四
执行线程:李四
执行线程:李四
执行线程:李四
执行了线程:张三
执行了线程:张三
yield方法会让出CPU的执行权,让线程调度器重新调度线程,但还是有一定的记录又再一次调用到出让CPU的线程上的,这一次他就会执行线程的方法了,因为yield已经被执行过了。
4. 获取当前线程

public class ThreadDemo {
public static void main(String[] args) {
Thread thread = Thread.currentThread();
System.out.println(thread.getName());
}
}
5. 休眠当前线程
休眠线程有两种实现:
a. 使⽤ sleep 休眠
b. 使⽤ TimeUnit 休眠
a. 使⽤ sleep 休眠

public class ThreadDemo {
public static void main(String[] args) throws InterruptedException {
System.out.println(System.currentTimeMillis());
Thread.sleep(3 * 1000);
System.out.println(System.currentTimeMillis());
}
}
b. 使⽤ TimeUnit 休眠
import java.util.concurrent.TimeUnit;
TimeUnit.DAYS.sleep(1);//天
TimeUnit.HOURS.sleep(1);//⼩时
TimeUnit.MINUTES.sleep(1);//分
TimeUnit.SECONDS.sleep(1);//秒
TimeUnit.MILLISECONDS.sleep(1000);//毫秒
TimeUnit.MICROSECONDS.sleep(1000);//微妙
TimeUnit.NANOSECONDS.sleep(1000);//纳秒









