1、线程状态
初始-NEW: Thread : 对象已经创建,但start 方法还没调用.
终止-TERMINATED: Thread 对象还在,内核中的线程已经没了
运行-RUNNABLE: 就绪状态(线程已经在 cpu 上执行了/线程正在排队等待上 cpu 执行)
超时等待-TIMED WAITING: 阻塞.由于 sleep 这种固定时间的方式产生的阻塞.
等待-WAITING: 阻塞.由于 wait 这种不固定时间的方式产生的阻塞.
阻塞-BLOCKED:阻塞.由于锁竞争导致的阻塞.(死锁)
2、NEW、RUNNABLE、TERMINATED
我们通过getState()这个方法来获取线程状态
public class demo {
public static void main(String[] args) {
Thread thread = new Thread(()->{
System.out.println("线程正在执行");
});
System.out.println(thread.getState());
thread.start();
System.out.println(thread.getState());
try {
thread.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("main线程执行");
System.out.println(thread.getState());
}
}
获取状态如下
3、BLOCKIED-阻塞
BLOCKED是由于线程竞争发生死锁而导致的状态
下面这段代码就会发生死锁
public class demo {
public static void main(String[] args) {
Object locker1 = new Object();
Object locker2 = new Object();
Thread thread1 = new Thread(()->{
synchronized (locker1){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
synchronized (locker2){
System.out.println("线程1进行了加锁");
}
}
});
Thread thread2 = new Thread(()->{
synchronized (locker2){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
synchronized (locker1){
System.out.println("线程2进行了加锁");
}
}
});
thread1.start();
thread2.start();
}
}
通过jconsole查看线程状态,可知线程1、2都进入了BLOCKED状态
4、WAITING状态
调用wait()方法,还未唤醒时,线程就处于WAITING状态
public class demo {
public static void main(String[] args) {
Object object = new Object();
Thread thread1 = new Thread(()->{
synchronized (object){
try {
object.wait();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
}
});
Thread thread2 = new Thread(()->{
synchronized (object){
object.notify();
}
});
thread1.start();
System.out.println(thread1.getState());
thread2.start();
}
}
查看状态