——————————————————————————————————————————————————————————————————————
线程状态
线程状态是指线程在生命周期内所处的阶段,主要包括以下几种状态本章通过三个案例来进行演示。
NEW、RUNNABLE、BLOCKED、WAITING、TIMED_WAITING、TERMINATED
NEW、RUNNABLE、TERMINATED
🌰:创建线程实例,观察调用start方法前后和线程结束后所处的状态。
public class state {
public static void main(String[] args) throws InterruptedException {
//创建线程实例
Thread thread = new Thread(() -> {
for(int i = 0; i < 10; i++) {
System.out.print(i + " ");
}
System.out.println();
});
System.out.println(thread.getState()); //打印创建线程实例后状态
thread.start(); //线程启动
System.out.println(thread.getState()); //打印调用start方法后状态
Thread.sleep(3000); //休眠3s以便于观察线程结束后状态
System.out.println(thread.getState()); //打印线程结束后状态
}
}
NEW:创建线程实例,并未调用start方法
RUNNABLE:调用start方法,由JVM调度执行,包括准备运行和运行中两种状态
TERMINATED:线程执行完毕,正常结束或因异常结束
WAITING、TIMED_WAITING
🌰示例一
public class state {
public static void main(String[] args) {
Object locker = new Object();
Thread t1 = new Thread(() -> {
synchronized (locker) {
try {
locker.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
},"t1"); //将线程命名为t1
t1.start();
Thread t2 = new Thread(() -> {
synchronized (locker) {
System.out.println("hello");
}
},"t2"); //将线程命名为t2
t2.start();
}
}
🌰示例二
public class state {
public static void main(String[] args) {
Object locker = new Object();
Thread t1 = new Thread(() -> {
synchronized (locker) {
try {
locker.wait(10000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
},"t1"); //将线程命名为t1
t1.start();
Thread t2 = new Thread(() -> {
synchronized (locker) {
System.out.println("hello");
}
},"t2"); //将线程命名为t2
t2.start();
}
}
示例一中t1线程开始执行start方法,率先获得锁执行到第8行进入等待状态,t2线程开始执行后获得t1释放的锁,打印hello但没有调用notify方法释放锁,所以t1线程一直处于等待状态。
示例二同示例一一样,唯一区别在于wait方法含有参数,在等待10秒后会自动结束线程,并不会和t1一样一直等待下去。
WAITING:等待唤醒一直等等到天荒地
TIMED_WAITING:同样是等待唤醒,给唤醒加了份期限
BLOCKED
🌰:同样引用上面的示例将wait换成sleep,观察俩个线程的状态
public class state {
public static void main(String[] args) {
Object locker = new Object();
Thread t1 = new Thread(() -> {
synchronized (locker) {
try {
Thread.sleep(60000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
},"t1"); //将线程命名为t1
t1.start();
Thread t2 = new Thread(() -> {
synchronized (locker) {
System.out.println("hello");
}
},"t2"); //将线程命名为t2
t2.start();
}
}
t1线程获取到锁之后进入到sleep状态,但是并不会释放锁,因此t2线程无法获取到锁一直处于阻塞状态
BLOCKED:在生命周期内,一个线程试图获取锁但锁被其它线程所持有,该线程就会进入阻塞状态