学习笔记-java线程基础
本文内容源于视频教程,若有侵权,请联系作者删除
一、线程生命周期
1.1 线程的六种状态
初始状态:线程被创建
运行状态:JAVA线程把操作系统中的就绪和运行两种状态统一称为“运行中”
阻塞状态:由于某种原因导致正在运行的线程让出CPU执行权限
等待状态:等待完成返回
超时等待状态:超时以后自动返回
终止状态:线程执行完毕或者被其他线程杀死。
1.1 查看线程状态
1 public class ThreadStatusDemo { 2 3 public static void main(String[] args) { 4 new Thread(()->{ 5 while (true){ 6 try { 7 Thread.sleep(100000); 8 } catch (InterruptedException e) { 9 e.printStackTrace(); 10 } 11 } 12 }, "sleep_thread").start(); 13 14 new Thread(()->{ 15 while (true){ 16 synchronized (ThreadStatusDemo.class) { 17 try { 18 ThreadStatusDemo.class.wait(); 19 } catch (InterruptedException e) { 20 e.printStackTrace(); 21 } 22 } 23 } 24 }, "wait_thread").start(); 25 26 BlockDemo blockDemo = new BlockDemo(); 27 new Thread(new BlockDemo(),"线程A").start(); 28 new Thread(new BlockDemo(),"线程B").start(); 29 } 30 31 static class BlockDemo extends Thread{ 32 @Override 33 public void run() { 34 synchronized (BlockDemo.class){ 35 try { 36 Thread.sleep(110000); 37 } catch (InterruptedException e) { 38 e.printStackTrace(); 39 } 40 } 41 } 42 } 43 }
打开terminal->输入jps命令,复制当前类的执行线程id->输入jstack 线程id查看当前进程中各线程状态。
1.2 启动和终止线程
1.2.1 启动线程
调用Thread.start()
1.2.2 线程中断
Thread.interrupt()优雅地中断线程。
1 public class InterruptDemo { 2 private static int i = 0; 3 4 public static void main(String[] args) { 5 Thread thread = new Thread(()->{ 6 while (!Thread.interrupted()){ 7 i++; 8 } 9 System.out.println("i=" + i); 10 }); 11 thread.start(); 12 try { 13 Thread.sleep(1000); 14 } catch (InterruptedException e) { 15 e.printStackTrace(); 16 } 17 thread.interrupt(); 18 } 19 }
每个线程都有一个中断标识,为了更好地理解,假设该变量为boolean isInterrupted=false 标识当前线程没有被中断,而调用Thread.interrupt()方法实质上就是将isInterrupted设置为true。具体细节可以通过hotspot源码看到。
1.2.2 线程复位
第一种方法:Thread.interrupted()
1 public class InterruptedDemo { 2 3 public static void main(String[] args) throws InterruptedException { 4 Thread thread = new Thread(()->{ 5 while (true){ 6 if (Thread.currentThread().isInterrupted()) { 7 System.out.println("before interrupted :" + Thread.currentThread().isInterrupted()); 8 Thread.interrupted(); 9 System.out.println("after interrupted :" + Thread.currentThread().isInterrupted()); 10 } 11 } 12 }); 13 thread.start(); 14 Thread.sleep(1000); 15 thread.interrupt(); 16 } 17 }
输出结果
before interrupted :true after interrupted :false
由此可见,Thread.interrupted()的作用实质上是设置isInterrupted为false
第二种方法:throw InterruptedException
1 public class ExceptionThreadDemo { 2 3 private static int i = 0; 4 5 public static void main(String[] args) { 6 7 Thread thread = new Thread(() -> { 8 while (!Thread.interrupted()) { 9 try { 10 Thread.sleep(1000); 11 } catch (InterruptedException e) { 12 e.printStackTrace(); 13 } 14 } 15 System.out.println("i=" + i); 16 }); 17 thread.start(); 18 try { 19 Thread.sleep(100); 20 } catch (InterruptedException e) { 21 e.printStackTrace(); 22 } 23 thread.interrupt(); 24 System.out.println(thread.isInterrupted()); 25 } 26 }