1.** NEW**
表示创建了一个线程,但是还没有启动时的状态。下面我们来做一个实验,代码如下:
public static void main(String[] args) {
Thread thread = new Thread();
Thread.State state = thread.getState();
System.out.println("state : "+state);
}
输出:
state : NEW
2.RUNNABLE
表示线程在运行中的状态。下面我们来做一个实验,代码如下:
public static void main(String[] args) {
Thread thread = new Thread(new Runnable() {
@Override
public void run() {
for (int i = 0; i < 10000000; i++) {
System.out.println(i);
}
}
});
thread.start();
}
dump 出线程的堆栈
3.BLOCKED
表示一个线程在等待锁,拿到这个锁后才能进入 synchronized 块或者 synchronized 方法。拿到这个锁之前一直处于阻塞状态。闲话少说,上代码:
public static void main(String[] args) {
final Object lock = new Object();
Runnable runnable = new Runnable() {
@Override
public void run() {
for (int i = 0; i < 1000000; i++) {
synchronized (lock) {
System.out.println(i);
}
}
}
};
Thread thread1 = new Thread(runnable);
thread1.setName("test-thread1");
thread1.start();
Thread thread2 = new Thread(runnable);
thread2.setName("test-thread2");
thread2.start();
}
笔者在IDEA里随机的dump了一下,线程1进入 synchronized 块,状态是RUNNABLE;线程2则等待锁,状态为BLOCKED
test-thread1 的线程堆栈如下:
test-thread2 的线程堆栈如下:
4.WAITING
源码里的注释说的是,一个线程在同一个对象锁上调用了 Object.wait(无参数)方法,或者Thread.join(无参数)方法, 或者LockSupport.park() 方法后,它状态是 WAITING。比如说,一个线程在一个同步块(Object Lock)内调用了Object.wait() 方法,那么这个线程的状态是 WAITING,直到另外一个线程在同一个Object Lock 上调用了Object.notify() 或者 Object.notifyAll() 方法,当前线程的状态才变更成 RUNNABLE
public static void main(String[] args) {
final Object lock = new Object();
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock) {
try {
lock.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("hello world");
}
}
});
Thread thread2 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (lock) {
for (int i = 0; i < 1000000; i++) {
System.out.println(i);
}
lock.notify();
}
}
});
thread1.setName("test-thread1 ");
thread1.start();
thread2.setName("test-thread2 ");
thread2.start();
}
线程1 start 之后调用了 wait 方法,紧接着线程2 start ,进入同步块之后开始打印,直到打印完毕,调用notify 方法唤醒 线程1
线程2 因为一直在循环打印,所以状态为 RUNNABLE
线程1 因为在 wait,所以状态为 WAITING
5.TIMED_WAITING
有时间限制的 WAITING
6.TERMINATED
线程执行完毕后的状态
public static void main(String[] args) {
Thread thread1 = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("thread run ...");
}
});
thread1.start();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(thread1.getState());
}
输出:
thread run ...
TERMINATED