1.线程有哪六种状态
New(新创建的) 新建线程还会执行start方法时的状态Runnable(可运行的) 调用了start方法后就会变成Runnable状态Blocked(被阻塞的) 进入到synchronized修饰的相关方法或代码块,但锁已被其他线程拿走Waiting(等待) 调用wait 或 join等方法不确定唤醒的时间,只能手工唤醒Timed-Waiting(计时等待) 等到固定时间后就能被唤醒,或使用手动唤醒的方式唤醒Terminated(已终止) 程序执行完毕或出现没有被捕获的异常,中止了run方法的运行2.打印 new runnable terminated 状态
public class ThreadLiftStyle implements Runnable{ @Override public void run() { for (int i = 0; i < 1000; i++) { System.out.println(i); } } public static void main(String[] args) { Thread thread = new Thread(new ThreadLiftStyle()); //应该是 new 状态 还未启动时的状态 System.out.println(thread.getState()); thread.start(); //调用start方法状态变为runnable状态 System.out.println(thread.getState()); try { Thread.sleep(10); } catch (InterruptedException e) { e.printStackTrace(); } // 在运行 显示的是runnable状态而不是running状态 System.out.println(thread.getState()); try { Thread.sleep(100); } catch (InterruptedException e) { e.printStackTrace(); } //运行结束 状态为 terminated System.out.println(thread.getState()); } } 结果: NEW RUNNABLE 0 1 ... 510 RUNNABLE 511 ... 999 TERMINATED3.打印 block waiting timed_waiting 状态
public class BlockedWaitingTimedWaiting implements Runnable{ @Override public void run() { syn(); } private synchronized void syn(){ try{ Thread.sleep(1000); wait(); }catch (InterruptedException e){ e.printStackTrace(); } } public static void main(String[] args) { BlockedWaitingTimedWaiting runnable = new BlockedWaitingTimedWaiting(); Thread thread1 = new Thread(runnable); thread1.start(); Thread thread2 = new Thread(runnable); thread2.start(); try { Thread.sleep(5); } catch (InterruptedException e) { e.printStackTrace(); } //打印出Timed_Waiting状态,因为正在执行Thread.sleep(1000); System.out.println(thread1.getState()); //打印出Blocked状态,因为thread2想拿到sync()的锁却拿不到 System.out.println(thread2.getState()); try { Thread.sleep(1300); } catch (InterruptedException e) { e.printStackTrace(); } //打印出WAITING状态,因为执行了wait() System.out.println(thread1.getState()); } } 结果: TIMED_WAITING BLOCKED WAITING4.面试问题
阻塞状态是什么一般来说,把Blocked(被阻塞)、Waiting(等待)、Timed_waiting(计时等待)都称为阻塞状态而不仅仅是Blocked状态
线程的生命周期有哪些1.new 2.runnable 3.blocked 4.waiting 5.timed_waiting 6.terminated 关于这六种状态的转换可以参考上方的图片