线程的生命周期
线程状态的转换
通过代码输出线程的状态,代码如下
public class ThreadState_ { public static void main(String[] args) { T t = new T(); System.out.println(t.getName() + " 状态 " + t.getState()); t.start(); while (Thread.State.TERMINATED != t.getState()) { //当t线程的状态,不等于终止状态 System.out.println(t.getName() + " 状态 " + t.getState()); try { Thread.sleep(500); } catch (InterruptedException e) { e.printStackTrace(); } } System.out.println(t.getName() + " 状态 " + t.getState()); } } class T extends Thread { @Override public void run() { while (true) { for (int i = 0; i < 10; i++) { System.out.println("hi" + i); try { Thread.sleep(1000); //休眠1秒钟 } catch (InterruptedException e) { e.printStackTrace(); } } break; } } }
输出状态如下
Thread-0 状态 NEW Thread-0 状态 RUNNABLE hi0 Thread-0 状态 TIMED_WAITING hi1 Thread-0 状态 TIMED_WAITING Thread-0 状态 TIMED_WAITING hi2 Thread-0 状态 TIMED_WAITING Thread-0 状态 TIMED_WAITING hi3 Thread-0 状态 TIMED_WAITING Thread-0 状态 TIMED_WAITING hi4 Thread-0 状态 TIMED_WAITING Thread-0 状态 TIMED_WAITING hi5 Thread-0 状态 TIMED_WAITING Thread-0 状态 TIMED_WAITING hi6 Thread-0 状态 TIMED_WAITING Thread-0 状态 TIMED_WAITING hi7 Thread-0 状态 TIMED_WAITING Thread-0 状态 TIMED_WAITING hi8 Thread-0 状态 TIMED_WAITING Thread-0 状态 TIMED_WAITING hi9 Thread-0 状态 TIMED_WAITING Thread-0 状态 TIMED_WAITING Thread-0 状态 TERMINATED