线程状态
此处以java.lang.Thread.State类中的6个状态分别说明,查看State类简介:
A thread state. A thread can be in one of the following states:
一个线程的状态,可以是以下状态之一:
NEW : A thread that has not yet started is in this state.
尚未启动的线程的状态。
RUNNABLE: A thread executing in the Java virtual machine is in this state.
可运行线程的状态,等待CPU调度。
BLOCKED: A thread that is blocked waiting for a monitor lock is in this state.
阻塞状态,线程阻塞等待监视器锁定的线程状态,处于synchronized同步代码块或方法中被阻塞。
WAITING: A thread that is waiting indefinitely for another thread to perform a particular action is in this state.
等待状态,不带超时的方式:Object.wait、Thread.join、LockSupport.park。
TIMED_WAITING: A thread that is waiting for another thread to perform an action for up to a specified waiting time is in this state.
带一定时间的等待,带超时的方式:Thread.sleep、Object.wait、Thread.join LockSupport.parkNanos、LockSupport.parkUntil。
TERMINATED: A thread that has exited is in this state.
终止线程的状态,线程正常完成执行,或出现异常。
线程间状态的转换如下图所示:
线程中止
stop() 和interrupt() 方式比较:
stop(): 强制中止线程,并且清除监控器锁(synchronized,lock)的消息,可能会导致线程安全问题。
interrupt():能够正确中止程序,并且不会在同步代码块中出现线程安全问题。
标志位实现代码中止:
public class ManualStop {
/* 标志位 */
volatile static boolean flag = true;
public static void main(String[] args) throws InterruptedException {
new Thread(() -> {
try {
while (flag) { // 判断是否运行
System.out.println("运行中");
Thread.sleep(1000L);
}
} catch (InterruptedException e) {
e.printStackTrace();
}
}).start();
Thread.sleep(3000L);
flag = false;
System.out.println("程序运行结束~");
}
}