线程的六个状态
- New :已创建,但未启动,还没有执行run()
- Runnable :从new调用了start转变为了runnable,这里的runnabled既可以代表可运行,又可以代表运行中的
- Blocked :当一个线程进入synchronized修饰的代码块,并且该锁已经被其他线程拿走了,这时候线程进入到了blocked,blocked的状态只针对于synchronized修饰的。
- Waiting :没有设置timeout的等待
- Timed Waiting:设置了timeout的等待
- Terminated:终止
展示线程的New、Runnable、Terminated状态
public class NewRunnableTerminated implements Runnable {
public static void main(String[] args) throws InterruptedException {
Thread thread = new Thread(new NewRunnableTerminated());
// 打印状态
System.out.println(thread.getState());
thread.start();
// 打印状态
System.out.println(thread.getState());
Thread.sleep(10);
System.out.println(thread.getState());
Thread.sleep(100);
System.out.println(thread.getState());
}
@Override
public void run() {
for (int i = 0; i < 1000; i++) {
System.out.println(i);
}
}
}
这里的打印就不贴了,可以直接复制代码运行一下。
输出的顺序是:NEW,RUNNABLE,RUNNABLE,TERMINATED
上面那段代码呢证明:即使线程是正在运行,也是Runnable状态,而不是Running ,这个就是第一次加入sleep原因,目的就是为了看到运行时候的Runnable状态
展示Blocked状态
public class BlockedWaitingTimedWaiting implements Runnable {
public static void main(String[] args) throws InterruptedException {
BlockedWaitingTimedWaiting runnable = new BlockedWaitingTimedWaiting();
Thread thread1 = new Thread(runnable);
thread1.start();
Thread thread2 = new Thread(runnable);
Thread.sleep(1000);
thread2.start();
// 打印出TIMED_WAITING,因为正在执行Thread.sleep(5000);
System.out.println(thread1.getState());
// 打印出BLOCKED状态,因为thread2想拿到syn()的锁却拿不到
System.out.println(thread2.getState());
}
@Override
public void run() {
syn();
}
private synchronized void syn() {
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
输出
我的代码中,在执行thread2.start()方法前加入了Thread.sleep(1000);是因为我本地运行的太快了,所以加入了一个sleep等待一下
TIMED_WAITING
BLOCKED
展示WAITTING状态
在刚才的代码基础上
public class BlockedWaitingTimedWaiting implements Runnable {
public static void main(String[] args) throws InterruptedException {
BlockedWaitingTimedWaiting runnable = new BlockedWaitingTimedWaiting();
Thread thread1 = new Thread(runnable);
thread1.start();
Thread thread2 = new Thread(runnable);
Thread.sleep(1000);
thread2.start();
// 打印出TIMED_WAITING,因为正在执行Thread.sleep(5000);
System.out.println(thread1.getState());
// 打印出BLOCKED状态,因为thread2想拿到syn()的锁却拿不到
System.out.println(thread2.getState());
Thread.sleep(1300);
// 打印出WAITTING,因为执行了wait方法
System.out.println(thread1.getState());
}
@Override
public void run() {
syn();
}
private synchronized void syn() {
try {
Thread.sleep(2000);
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
输出
TIMED_WAITING
BLOCKED
WAITING
一般而言,把Blocked、Waiting、Timed_waiting都称为阻塞状态