本章我们主要讲Java线程的运行状态:
从Thred类的源码中可以看到线程状态一共有六种。
public enum state{
NEW,
RUNNABLE,
BLOCKED,
WATINTING,
TIMED_WAITING,
TERMINATED
}
NEW(新建):指的是刚刚创建的线程,并没有调用start方法。
RUNNABLE(可运行):指的是线程调用start方法,等待CPU调度。
BLOCKED(阻塞):当一个线程试图获取对象锁的时候,对象锁被其它线程持有,此时就会进入BLOCKED,如果获得对象锁则进入RUNNABLE状态。
WAITING(无限等待):一个线程在等待另一个线程唤醒,该线程进入WAITING状态,如果没有其它线程执行notify或notifyAll(这两个的区别是notify就唤醒这一个线程,而notifyAll唤醒的是所有处于WAITING状态的线程)。
TIMED_WAITING(计时等待):带有超时参数的例如有Thread.sleep()、Object.wait(),将进入TIMED_WAITING状态,等待时间到达,或接收到唤醒通知,才结束这个状态。
TERMINATED(被终止):线程执行结束或或者因为没有捕获异常而终止了run方法的运行。
运行状态转换图:
下面来代码演示一下每种状态的获得:
NEW(新建):
public class ThreadDemo3 {
public static void main(String[] args) {
Thread t = new Thread(new Ticket());
System.out.println(t.getState());//NEW
}
static class Ticket implements Runnable{
@Override
public void run() {
System.out.println("hello world");
}
}
}
RUNNABLE(可运行的):
public class ThreadDemo3 {
public static void main(String[] args) {
Thread t = new Thread(new Ticket());
t.start();
System.out.println(t.getState());//RUNNABLE
}
static class Ticket implements Runnable{
@Override
public void run() {
System.out.println("hello world");
}
}
}
BLOCKED(阻塞的)和WAITING(无限等待):
public class ThreadDemo7 {
public static void main(String[] args) {
Object object = new Object();
Thread t1 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (object){
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
}
}
});
System.out.println(t1.getState());
Thread t2 = new Thread(new Runnable() {
@Override
public void run() {
synchronized (object){
try {
object.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName());
}
}
});
t1.start();
t2.start();
while (true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(t2.getState());
}
}
}
TIMED_WAITING(计时等待):
public class ThreadDemo9 {
public static void main(String[] args) {
Object object = new Object();
Thread t = new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(10000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
});
t.start();
while (true){
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(t.getState());
}
}
}
TERMINATED(被终止):
public class ThreadDemo8 {
public static void main(String[] args) {
Thread t = new Thread(new Runnable() {
@Override
public void run() {
/*System.out.println("hello world");*/
}
});
t.start();
System.out.println(t.getState());//RUNNABLE
System.out.println(t.getState());//TERMINATED
}
}
其实在这里我开始有疑惑,为何第一个获得的状态第一个为何总是RUNNABLE,第二个获得的线程状态才是TERMINATED,后来想明白了因为调用start()方法后当然会是RUNNABLE状态,而后运行完成后才会是TERMINATED状态。