线程的几种状态如图:
🍁New,线程刚创建的状态。
🍁Runnable,表示线程正在运行或者准备运行。
🍁Terminated,终止状态,也可以说是死亡状态,此时线程代码执行完毕。
🍁Timed-Waiting,超时等待状态,即线程等待一段时间后继续执行。
🍁Blocked,线程阻塞状态,多个线程之间竞争锁,没拿到锁的线程就会进入阻塞状态。
🍁Waiting,等待状态。线程拿到锁后,锁对象调用wait()
方法,线程释放锁并进入等待状态。
我们创建了Thread对象后,就处于New状态。
下面是代码演示:
public class NewState {public static void main(String[] args) {Thread t = new Thread(()->{});System.out.println(t.getState());}
}
执行结果:
当我们调用线程对象的start()
方法后,线程就从New状态变成了Runnable状态。
public class RunnableState {public static void main(String[] args) {Thread t = new Thread(()->{});System.out.println("调用start()方法前: " + t.getState());t.start();System.out.println("调用start()方法后: " + t.getState());}
}
当我们让一个线程睡眠的时候,就会从Runnable状态转换到Timed-Waiting。
翻译成中文叫超时等待,我觉得这个翻译过后没那么好理解。
直接看英文会很好理解,Timed表示有时间的,Waiting表示等待。
创建t线程后,启动线程。
让main线程睡眠0.5秒(保证t线程执行sleep()方法),然后打印t线程状态。
public class TimedWaitingState {public static void main(String[] args) throws InterruptedException{Thread t = new Thread(()->{try {Thread.sleep(2000);} catch (InterruptedException e) {e.printStackTrace();}});t.start();Thread.sleep(500);System.out.println(t.getState());}
}
当多个线程去竞争同一个琐时,没竞争到锁的线程,就处于Blocked状态。
下图可以说明,锁竞争的一个大致过程。
开启两个线程t1和t2去竞争锁,让拿到锁的线程把所有的线程的状态都打印出来。
下面是代码的演示:
public class BlockedState {public static Object lock = new Object();public static void main(String[] args) {Thread t1 = new Thread(()->{synchronized (lock) {//获取ThreadGroup对象ThreadGroup threadGroup = Thread.currentThread().getThreadGroup();//创建Thread数据Thread[] list = new Thread[threadGroup.activeCount()];//把所有的线程对象,添加到list中threadGroup.enumerate(list);for (Thread thread : list) {System.out.println("Thread: " + thread.getName() + " State: " + thread.getState());}System.out.println();}}, "t1");Thread t2 = new Thread(()->{synchronized (lock) {//获取ThreadGroup对象ThreadGroup threadGroup = Thread.currentThread().getThreadGroup();//创建Thread数据Thread[] list = new Thread[threadGroup.activeCount()];//把所有的线程对象,添加到list中threadGroup.enumerate(list);for (Thread thread : list) {System.out.println("Thread: " + thread.getName() + " State: " + thread.getState());}System.out.println();}}, "t2");t1.start();t2.start();}
}
执行结果:
解释:t1先拿到锁,t2从Runnable状态进入Blocked状态。
当一个线程拿到锁后,调用锁对象的wait()
方法,线程就会释放锁,并从Runnable状态变为Waiting状态 。
public class WaitingState {public static Object lock = new Object();public static void main(String[] args) throws InterruptedException{Thread t = new Thread(()-> {synchronized (lock) {try {lock.wait();} catch (InterruptedException e) {e.printStackTrace();}}}, "t");t.start();Thread.sleep(1000);System.out.println("state: " + t.getState());}
}
当一个线程run()
方法执行完成之后,线程的状态就变成了Terminated状态。
创建一个线程t并启动,让main线程先睡眠一秒后
获取t线程的状态,此时t线程的状态就是Terminated状态。
public class TerminatedState {public static void main(String[] args) {Thread t = new Thread(()->{}, "t");t.start();try {Thread.sleep(1000);} catch (InterruptedException e) {e.printStackTrace();}System.out.println("Thread: " + t.getName() + " State: " + t.getState());}
}
运行截图: