1.6 线程状态
线程的方法
关于停止线程
一般不建议使用jdk提供的stop()和destroy()方法,推荐线程自己停下来,建议使用一个标志位flag=false;来终止变量。
线程休眠
-
模拟网络延迟,放大问题的发生性
-
模拟倒计时
线程礼让
让当前执行的线程暂停,但不阻塞,使线程从运行状态转为就绪状态。让cpu重新调度,礼让不一定成功。
join合并线程(插队)
Thread.State
package com.ty.test;
public class StateTest {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
for (int i = 0; i < 5; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
System.out.println(“线程结束了…”);
});
//观察状态
Thread.State state = thread.getState();
System.out.println(state);
//观察启动
thread.start();
state = thread.getState();
System.out.println(state);
while (state != Thread.State.TERMINATED) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
state = thread.getState();
System.out.println(state);
}
}
}
NEW
RUNNABLE
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
RUNNABLE
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
RUNNABLE
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING
TIMED_WAITING