Java中线程的状态
在Java当中把对线程的状态分得比原生操作系统更加细致,在
Thread
类内部,定义了一个枚举类型State
,定义了线程的6种状态,如下
public enum State {
NEW,
RUNNABLE,
BLOCKED,
WAITING,
TIMED_WAITING,
TERMINATED;
}
NEW:
线程刚创建出来,还未执行start()
方法之前处于NEW
状态.Thread thread = new Thread(new ThreadMethod()); System.out.println("thread.getState() = " + thread.getState());
2.
RUNNABLE:
线程处于运行状态或者处在就绪队列,等待CPU资源Thread thread = new Thread(new ThreadMethod()); System.out.println("thread.getState() = " + thread.getState()); thread.start(); System.out.println("thread.getState() = " + thread.getState());
3.
TERMINATED
结束状态,表示线程已经执行完毕Thread thread = new Thread(new ThreadMethod()); System.out.println("thread.getState() = " + thread.getState()); thread.start(); System.out.println("thread.getState() = " + thread.getState()); Thread.sleep(100); System.out.println("thread.getState() = " + thread.getState());
4.
BLOCKED:
这个状态表示线程正在等待锁资源public class ThreadDemo implements Runnable { private static final Object lock = new Object(); public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(new ThreadDemo()); thread.start(); Thread thread1 = new Thread(new ThreadDemo()); thread1.start(); Thread.sleep(1000); System.out.println("thread1.getState() = " + thread1.getState()); } @Override public void run() { synchronized (lock){ System.out.println(Thread.currentThread().getName()+" synchronized 加锁"); // 休眠 5 秒 try { Thread.sleep(5000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(Thread.currentThread().getName()+" synchronized 释放锁"); } } }
可以看到,当
thread
开始执行时,进入synchronized
代码块,而后来的线程thread
因为无法进入synchronized
而阻塞,进入BLOCKED
状态
5.
WAITING:
查看源码–>
发现,当线程调用上面3个方法时,会进入WAITING
状态
如:
public class ThreadState implements Runnable{ @Override public synchronized void run() { while (true) { try { this.wait(); this.notify(); } catch (InterruptedException e) { e.printStackTrace(); } } } public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(new ThreadState()); thread.start(); Thread.sleep(1000); System.out.println("thread.getState() = " + thread.getState()); } }
6.
TIMED_WAITING:
查看源码–>
当线程进入有限等待时进入TIMED_WAITING
状态.
如:
public class ThreadState implements Runnable{ @Override public void run() { try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } } public static void main(String[] args) throws InterruptedException { Thread thread = new Thread(new ThreadState()); thread.start(); Thread.sleep(1000); System.out.println("thread.getState() = " + thread.getState()); } }
输出
同理join()与wait()带参数的版本可以达到同样的效果