线程的状态
public enum State {
NEW, RUNNABLE, BLOCKED, WAITING, TIMED_WAITING, TERMINATED;
}
验证状态
NEW 新建线程
Thread thread = new Thread(() -> {
});
System.out.println(thread.getState());
Runnable 运行状态(包括ready和running)
Thread thread = new Thread(() -> {
});
thread.start();
System.out.println(thread.getState());
Blocked 阻塞状态
Object obj = new Object();
new Thread(() -> {
synchronized (obj) {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}).start(); // 获取锁后不释放
Thread thread = new Thread(() -> {
synchronized (obj) {
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});//线程获取不到锁就会处于blocked状态。
thread.start();
System.out.println(thread.getState());
while (true) {
Thread.sleep(1000);
}
}
第一个线程synchronized 获取锁后休眠,不释放锁。
第二个线程,synchronized 获取不到锁会被挂起。那么最后的输出结果就会是BLOCKED
Waiting 等待(可被唤醒)
Object obj = new Object();
Thread thread = new Thread(() -> {
synchronized (obj) {
try {
obj.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();
while (true) {
Thread.sleep(1000);
System.out.println(thread.getState());
}
只要在 synchronized 代码块或者修饰的方法中调用 wait 方法,又没有被 notify 就会进入 WAITING 状态。
另外 Thread.join 源码中也是调用的 wait 方法,所以也会让线程进入等待状态。
timed_waiting 超时等待
Object obj = new Object();
Thread thread = new Thread(() -> {
synchronized (obj) {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
thread.start();
while (true) {
Thread.sleep(1000);
System.out.println(thread.getState());
}
Thread.sleep(10000);
睡眠状态不释放锁,处于超时等待状态。
Terminated 终止状态
Thread thread = new Thread(() -> {
});
thread.start();
System.out.println(thread.getState());// runnible
System.out.println(thread.getState());// terminated
System.out.println(thread.getState()); //terminated
线程执行完就会进入到terminated状态。