一:线程的6种状态
- NEW:表示已创建,但还没有启动的新线程
- Runnable:线程新建后调用star方法进入此状态,相当于操作系统的ready,running状态,即有可能在运行也有可能没在运行
- Blocked:线程在进入synchonized关键字修饰的代码中没有获得锁。
- wait:调用Object类的wait方法和Thread的join方法以及LockSupport.park()进入此状态
- TimeWaiting:等待超时,超时后会被自动唤醒,如果在超时之前收到信息,也会被唤醒
- Terminated:一是run方法正常运行结束,二是出现没有被捕获的异常导致run方法异常终止
二:代码实现各状态的演示
/**
* 展示线程的NEW,RUNNABLE,TERMINATED状态,即使正在运行,也是Runnable状态
* 而不是Running
*/
public class NewRunnableTerMinated implements Runnable{
@Override
public void run() {
for (int i=0;i<1000;i++){
System.out.println(i);
}
}
public static void main(String[] args) {
Thread thread=new Thread(new NewRunnableTerMinated());
//新建后未启动
System.out.println("启动之前的状态是:"+thread.getState());
thread.start();
//启动之后的状态
System.out.println("启动之后的状态是:"+thread.getState());
try {
Thread.sleep(10);
} catch (InterruptedException e) {
e.printStackTrace();
}
//在运行过程种获取它的状态
System.out.println(thread.getState());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//运行完之后的状态
System.out.println("运行完之后的状态是:"+thread.getState());
}
}
/**
* 展示Blocked,Waiting,TimeWaiting三种状态
*/
public class BlockedWaitingTimeWaiting implements Runnable{
public static void main(String[] args) {
BlockedWaitingTimeWaiting runnable=new BlockedWaitingTimeWaiting();
Thread thread1=new Thread(runnable);
thread1.start();
Thread thread2=new Thread(runnable);
thread2.start();
//打印出TimeWaiting状态,因为执行了Thread.sleep(1000);进入限期等待状态
System.out.println("线程thread1的状态是:"+thread1.getState());
//打印出Blocked状态,因为thread2想拿到syn的锁,却拿不到
System.out.println("线程thread2的状态是:"+thread2.getState());
try {
Thread.sleep(1300);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("线程thread1的状态是:"+thread1.getState());
}
@Override
public void run() {
syn();
}
private synchronized void syn() {
try {
//持有锁1秒钟,在此期间,其他线程不能得到这把锁
Thread.sleep(1000);
wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
三:状态间的转换图示
四:什么是阻塞状态?
Blocked不完全等于阻塞,因为Blocked只是阻塞状态的一种,一般将阻塞分为:
- Blocked
- Waiting
- Timewaiting
五:面试题?
线程有哪些状态?即生命周期