Java线程生命周期图文详细讲解
作者:健鑫. 时间:2022-07-17 05:22:32
线程的状态
New
表示线程已创建,没启动的状态
此时已经做了一些准备工作,还没有执行run方法中代码
Runnable
调用start方法之后的状态,表示可运行状态(不一定正在运行,因为调用start方法之后不一定立即运行)
如果线程拿到CPU资源,但是突然资源被抢走,这个线程依然处于Runnable
Blocked
线程进入到被synchronized修饰的代码块时,该锁已经被其他线程拿走,此时该线程处于Blocked
Blocked只针对synchronized
Waiting
没有设置时间参数的Object.wait方法可使线程状态变为waiting
Timed Waiting
相对Waiting,有了时间参数
Terminated
执行完毕
run方法正常执行完毕
或者出现了一个没有被捕获的异常终止了run方法
代码演示
展示线程的New、Runnable、Terminated状态
线程刚被new处于NEW状态
调用start方法处于RUNNABLE状态
程序正在执行处于RUNNABLE状态而不是RUNNING
程序结束处于TERMINATED状态
public class NewRunnableTerminated implements Runnable {
public static void main(String[] args) {
Thread thread = new Thread(new NewRunnableTerminated());
// 打印线程状态
// New
System.out.println(thread.getState());
thread.start();
// Runnable
System.out.println(thread.getState());
// try {
// Thread.sleep(100);
// } catch (InterruptedException e) {
// e.printStackTrace();
// }
// Runnable
System.out.println(thread.getState());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
// TERMINATED
System.out.println(thread.getState());
}
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
System.out.println(i);
}
}
}
/*
* NEW
RUNNABLE
RUNNABLE
* TERMINATED
* */
演示waiting、Blocked、Timed Waiting
中间频繁调用sleep方法是防止代码执行太快,达不到应有的效果
线程被调用sleep,处于TIMED_WAITING
当一个线程执行synchronized内的代码,另一个线程也要执行则该线程处于BLOCKED
线程执行wait方法,处于WAITING
public class BlockWaitingTimedWaiting implements Runnable{
public static void main(String[] args) {
BlockWaitingTimedWaiting blockWaitingTimedWaiting = new BlockWaitingTimedWaiting();
Thread thread1 = new Thread(blockWaitingTimedWaiting);
thread1.start();
Thread thread2 = new Thread(blockWaitingTimedWaiting);
thread2.start();
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(thread1.getState());
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(thread2.getState());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(thread1.getState());
}
@Override
public void run() {
syn();
}
private synchronized void syn() {
try {
Thread.sleep(1000);
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
/*
* TIMED_WAITING
BLOCKED
WAITING
* */
阻塞状态
一般而言,Blocked、Waiting、Timed_waiting都被称之为阻塞状态
在阻塞状态下,什么时候可以继续执行是不受控制的
来源:https://blog.csdn.net/weixin_62759952/article/details/128764220