1.使用interrupt()中断线程
首先来看一段代码:
public class InterruptTest01 { public static class m1 implements Runnable { public void run() { try { System.out.println("in run() - 睡眠20秒"); Thread.sleep(20000); System.out.println("in run() - 线程唤醒"); } catch (Exception e) { System.out.println("in run() - 线程睡眠中被打断了"); // 如果没有return,线程不会实际被中断,它会继续打印下面的信息 System.out.println("t线程sleep中被打断后中断标志位状态:" + Thread.interrupted()); return; } System.out.println("in run() - 线程正常的消亡了"); } } public static void main(String[] args) { m1 si = new m1(); Thread t = new Thread(si); // 开启t线程 t.start(); System.out.println("调用interrupt方法前,t线程的中断状态:" + t.isInterrupted()); try { // 仅仅是做标记 t.interrupt(); System.out.println("调用interrupt方法后,t线程的中断状态:" + t.isInterrupted()); // 主线程休眠2秒,从而确保刚才启动的线程有机会执行一段时间 Thread.sleep(2000); } catch (InterruptedException e) { System.err.println("主线程catch块出问题了"); } System.out.println("in main() - 主线程终止了"); } }
执行结果:
调用interrupt方法前,t线程的中断状态:false 调用interrupt方法后,t线程的中断状态:true in run() - 睡眠20秒 in run() - 线程睡眠中被打断了 t线程sleep中被打断后中断标志位状态:false in main() - 主线程终止了