栈与栈帧:
Java 虚拟机栈会为每个启动的线程分配一块栈内存,其中存储着栈帧(Frame)
main
, method1
, method2
各自对应这一个栈帧,存储在一个栈中:
public class d1_Frame {
public static void main(String[] args) {
method1(10); // 调用method1
}
public static void method1(int x){
int y = x + 1;
Object obj = method2(); // 调用 method2
}
public static Object method2(){
Object obj = new Object();
return obj;
}
}
包含两个线程 main
和 t1
,分别创建两个独立的栈,每个栈里包含各自的栈帧
main
线程的栈:
t1
线程的栈:
public class d1_Frame {
public static void main(String[] args) {
Thread t1 = new Thread() {
@Override
public void run() {
method1(20); // t1 线程调用 method1
}
};
t1.setName("t1");
t1.start();
method1(10); // main 调用method1
}
public static void method1(int x){
int y = x + 1;
Object obj = method2(); // 调用 method2
}
public static Object method2(){
Object obj = new Object();
return obj;
}
}
线程上下文切换是指:CPU不再执行当前线程,转而执行其他线程的代码的过程
发生 Context Switch 的原因:
当 Context Switch 发生时,需要由操作系统保存当前线程的状态,并恢复另一个线程的状态,Java 中对应的概念
就是程序计数器(Program Counter Register),它的作用是记住下一条 jvm
指令的执行地址,是线程私有的
run调用:直接调用 run 方法,则是 main 主线程执行的,并没有创建一个新线程执行
start调用:创建一个新的线程 t1
,t1
线程与 main
线程是同时进行的。调用后,线程的状态也会发生改变
@Slf4j(topic = "c.d2_run_start")
public class d2_run_start {
public static void main(String[] args) {
Thread t1 = new Thread("t1") {
@Override
public void run() {
log.debug("running");
}
};
t1.run();
// 14:25:50 [main] c.d2_run_start - running
System.out.println(t1.getState()); //NEW
t1.start();
// 14:28:11 [t1] c.d2_run_start - running
System.out.println(t1.getState()); // RUNNABLE
}
}
@Slf4j(topic = "c.d3_sleep_yield")
public class d3_sleep_yield {
public static void main(String[] args) {
Thread t1 = new Thread("t1"){
@Override
public void run() {
log.debug("running");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
};
log.debug("t1 state: {}", t1.getState()); // NEW
t1.start();
log.debug("t1 state: {}", t1.getState()); // RUNNABLE
try {
Thread.sleep(500);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.debug("t1 state: {}", t1.getState()); // TIMED_WAITING
}
}
InterruptedException
异常@Slf4j(topic = "c.d3_sleep_yield")
public class d3_sleep_yield {
public static void main(String[] args) {
Thread t1 = new Thread("t1"){
@Override
public void run() {
log.debug("enter sleep");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
log.debug("wake up ...");
e.printStackTrace();
}
}
};
t1.start();
try {
Thread.sleep(1000); // 当前 main 线程睡眠1s
log.debug("interrupt...");
t1.interrupt(); // 打断 t1 的 sleep
} catch (InterruptedException e) {
e.printStackTrace();
}
/**
* 输出:
* 14:45:29 [t1] c.d3_sleep_yield - enter sleep
* 14:45:30 [main] c.d3_sleep_yield - interrupt...
* 14:45:30 [t1] c.d3_sleep_yield - wake up ...
* java.lang.InterruptedException: sleep interrupted
*/
}
}
睡眠结束后的线程未必会立刻得到执行。睡眠结束后的线程仅仅是被唤醒了,还需要等待CPU分配时间片才能执行
TimeUnit
的 sleep 代替 Thread 的 sleep 来获得更好的可读性
iimport java.util.concurrent.TimeUnit;
// 该方法实际上是封装的 Thread.sleep 方法
TimeUnit.SECONDS.sleep(1); // 睡眠 1 s
yield(让出):让出当前线程 CPU 的使用权给其他线程
调用 yield 会让当前线程从 Running 进入 Runnable 就绪状态,然后调度执行其它线程
具体的实现依赖于操作系统的任务调度器
public class d4_thread_priority {
public static void main(String[] args) {
Thread t1 = new Thread(()->{
int count = 0;
while(true){
System.out.println("---> 1 " + count++);
}
}, "t1");
Thread t2 = new Thread(()->{
int count = 0;
while(true){
// Thread.yield();
System.out.println(" ---> 2 " + count++);
}
}, "t2");
// 设置线程优先级(默认优先级为5)
t1.setPriority(Thread.MIN_PRIORITY);
t2.setPriority(Thread.MAX_PRIORITY);
t1.start();
t2.start();
}
}
t1
的 count 会比 t2
的大t2
的 count 会比 t1
的大等待当前线程运行完毕
单线程等待:主线程 main 在同步等待 t1
线程
@Slf4j(topic = "c.d5_join")
public class d5_join {
static int r = 0;
public static void main(String[] args) throws InterruptedException {
test1();
}
private static void test1() throws InterruptedException {
log.debug("开始");
Thread t1 = new Thread(() -> {
log.debug("开始");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
log.debug("结束");
r = 10;
});
t1.start();
t1.join(); // 等待 t1 完成,再获取 r的结果
log.debug("结果为:{}", r);
log.debug("结束");
}
}
多线程等待:
@Slf4j(topic = "c.d5_join")
public class d5_join {
static int r1 = 0;
static int r2 = 0;
public static void main(String[] args) throws InterruptedException {
test2();
}
private static void test2() throws InterruptedException {
Thread t1 = new Thread(() -> {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
r1 = 10;
});
Thread t2 = new Thread(() -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
r2 = 20;
});
long start = System.currentTimeMillis();
t1.start();
t2.start();
t1.join();
t2.join();
long end = System.currentTimeMillis();
log.debug("r1: {} r2: {} cost: {}", r1, r2, end - start);
// 15:23:57 [main] c.d5_join - r1: 10 r2: 20 cost: 2014
}
先调用 t1 的 join 再调用 t2 的join,等待时间为 2s
颠倒两个 join 最终都是输出 2s
有时效的 join:
t1.join(1500); // 等待1.5后继续当前线程
// 如果 t1 仅需要 1s 完成,则join也会提前结束
打断后的打断标记为 false
(认为对 sleep,wait,join的线程进行打断不算打断)
@Slf4j(topic = "c.d6_interrupt")
public class d6_interrupt {
public static void main(String[] args) throws InterruptedException {
test1();
}
private static void test1() throws InterruptedException {
Thread t1 = new Thread(()->{
log.debug("sleep...");
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}, "t1");
t1.start();
Thread.sleep(500);
log.debug("interrupt...");
t1.interrupt();
log.debug(" 打断状态: {}", t1.isInterrupted());
/** 输出:
* 15:36:35 [t1] c.d6_interrupt - sleep...
* 15:36:36 [main] c.d6_interrupt - interrupt...
* 15:36:36 [main] c.d6_interrupt - 打断状态: false
*/
}
}
打断后的打断标记为 true
。但是被打断的线程并不会停止运行
这样可以通过一个标记让该线程获取自己被其他线程打断了,以便进行后续处理并决定是否停止当前线程
@Slf4j(topic = "c.d6_interrupt")
public class d6_interrupt {
public static void main(String[] args) throws InterruptedException {
test2();
}
private static void test2() throws InterruptedException {
Thread t2 = new Thread(()->{
while(true) {
// 获取当前线程的打断标记
Thread current = Thread.currentThread();
boolean interrupted = current.isInterrupted();
// 自己决定是否退出当前线程
if(interrupted) {
log.debug(" 打断状态: {}", interrupted);
// 15:39:55 [t2] c.d6_interrupt - 打断状态: true
break;
}
}
}, "t2");
t2.start();
Thread.sleep(500);
t2.interrupt();
}
}
Two Phase Termination
在一个线程 T1 中如何“优雅”终止线程 T2?这里的【优雅】指的是给 T2 一个料理后事的机会。
注意事项:
sleep过程中被打断会重置打断标记为false,所以需要重新设置打断标记为 true,以便在上面的if里判断标记,进行后续处理
如果不重新设置打断标记为 true,则不会进行料理后事的处理
class Test{
public static void main(String[] args) throws InterruptedException {
d7_two_phase_termination tpt = new d7_two_phase_termination();
tpt.start();
Thread.sleep(3500);
tpt.stop();
/** 输出:
* 16:07:57 [Thread-0] c.d7_two_phase_termination - 执行监控记录
* 16:07:58 [Thread-0] c.d7_two_phase_termination - 执行监控记录
* 16:07:59 [Thread-0] c.d7_two_phase_termination - 执行监控记录
* java.lang.InterruptedException: sleep interrupted
* at java.base/java.lang.Thread.sleep0(Native Method)
* at java.base/java.lang.Thread.sleep(Thread.java:509)
* at com.rainsun.d2_run_thread.d7_two_phase_termination.lambda$start$0(d7_two_phase_termination.java:30)
* at java.base/java.lang.Thread.run(Thread.java:1583)
* 16:08:00 [Thread-0] c.d7_two_phase_termination - 释放资源,锁,料理后事...
*/
}
}
@Slf4j(topic = "c.d7_two_phase_termination")
public class d7_two_phase_termination {
private Thread monitor;
// 启动监控程序
public void start(){
monitor = new Thread(()->{
while (true){
Thread currentThread = Thread.currentThread();
if(currentThread.isInterrupted()){
log.debug("释放资源,锁,料理后事...");
break;
}
try {
Thread.sleep(1000); // 情况一:sleep过程被打断
log.debug("执行监控记录"); // 情况二:执行其他过程被打断
} catch (InterruptedException e) {
e.printStackTrace();
// sleep过程中被打断会重置打断标记为false
// 这里需要重新设置打断标记为 true,以便在上面的if里判断标记,进行后续处理
currentThread.interrupt();
}
}
});
monitor.start();
}
public void stop(){
monitor.interrupt();
}
}
默认情况下,Java 进程需要等待所有线程都运行结束,才会结束。
t1
,main
,main线程结束了, t1
线程没结束则Java进程会继续运行有一种特殊的线程叫做守护线程,只要其它非守护线程运行结束了,即使守护线程的代码没有执行完,也会强制结束。
t1.setDaemon(true)
t1
2s才运行完,但是 t1
被设置为守护线程,当其他线程 1s后运行完后,t1
线程也被迫停止了
@Slf4j(topic = "c.d8_daemon")
public class d8_daemon {
public static void main(String[] args) throws InterruptedException {
log.debug("开始运行...");
Thread t1 = new Thread(() -> {
log.debug("开始运行...");
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
log.debug("运行结束...");
}, "daemon");
// 设置该线程为守护线程
t1.setDaemon(true);
t1.start();
Thread.sleep(1000);
log.debug("运行结束...");
/**
* 16:22:39 [main] c.d8_daemon - 开始运行...
* 16:22:39 [daemon] c.d8_daemon - 开始运行...
* 16:22:40 [main] c.d8_daemon - 运行结束...
*/
}
}
注意
六种状态的演示:
@Slf4j(topic = "c.d9_thread_state")
public class d9_thread_state {
public static void main(String[] args) throws InterruptedException {
Thread t1 = new Thread(()->{
log.debug("running..."); // NEW
}, "t1");
Thread t2 = new Thread(()->{
while (true){ // RUNNABLE
}
}, "t2");
t2.start();
Thread t3 = new Thread(()->{
log.debug("running..."); // TERMINATED
}, "t3");
t3.start();
Thread t4 = new Thread(()->{
synchronized (d9_thread_state.class){
try {
Thread.sleep(1000000); // timed_waiting
}catch (InterruptedException e){
e.printStackTrace();
}
}
}, "t4");
t4.start();
Thread t5 = new Thread(()->{
try {
t2.join(); // t5等待t2完成,t2为死循环,所以是 waiting状态
} catch (InterruptedException e) {
e.printStackTrace();
}
}, "t5");
t5.start();
Thread t6 = new Thread(()->{
// 这个锁已经被t4占据了,所以t6拿不到这个锁。陷入 blocked状态
synchronized (d9_thread_state.class){
try {
Thread.sleep(1000000);
}catch (InterruptedException e){
e.printStackTrace();
}
}
}, "t6");
t6.start();
Thread.sleep(500);
log.debug("t1 state {}", t1.getState());
log.debug("t2 state {}", t2.getState());
log.debug("t3 state {}", t3.getState());
log.debug("t4 state {}", t4.getState());
log.debug("t5 state {}", t5.getState());
log.debug("t6 state {}", t6.getState());
/** 输出:
* 16:47:45 [t3] c.d9_thread_state - running...
* 16:47:46 [main] c.d9_thread_state - t1 state NEW
* 16:47:46 [main] c.d9_thread_state - t2 state RUNNABLE
* 16:47:46 [main] c.d9_thread_state - t3 state TERMINATED
* 16:47:46 [main] c.d9_thread_state - t4 state TIMED_WAITING
* 16:47:46 [main] c.d9_thread_state - t5 state WAITING
* 16:47:46 [main] c.d9_thread_state - t6 state BLOCKED
*/
}
}