Java 多线程(二)之线程状态及其验证 (2)

先创建一个 Runnable 子类

public static void main(String[] args) { Thread thread = new Thread(new Runnable() { final Object lock = new Object(); public void run() { synchronized (lock) { try { lock.wait(); } catch (InterruptedException e) { } } } }); thread.start(); System.out.println(thread.getName()+" state :"+thread.getState()); try { Thread.sleep(1000L); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println(thread.getName()+" state :"+thread.getState()); }

测试方法

public static void main(String[] args) { BlockedStateRun blockedStateRun = new BlockedStateRun(); Thread thread1= new Thread(blockedStateRun); Thread thread2= new Thread(blockedStateRun); thread1.setName("First"); thread1.start(); thread2.setName("Second"); thread2.start(); try { Thread.sleep(200L); System.out.println(thread1.getName()+"::"+thread1.getState()); System.out.println(thread2.getName()+"::"+thread2.getState()); } catch (InterruptedException e) { e.printStackTrace(); } }

最后的运行结果:

状态转换

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/wpfssg.html