调用某线程的interrupt方法给该线程打上中断标识,当被标识中断的线程处于sleep、wait、join等阻塞状态时则会抛出InterruptedException异常
public static void main(String[] args){ Thread thread1 = new Thread(() -> { System.out.println("执行中"); try { TimeUnit.SECONDS.sleep(500); System.out.println("被唤醒"); } catch (InterruptedException e) { System.out.println("报错"); e.printStackTrace(); } System.out.println("其他操作"); } , "thread1"); thread1.start(); Thread thread2 = new Thread(() -> { Scanner scanner = new Scanner(System.in); String next = scanner.next(); thread1.interrupt(); System.out.println("thread2执行完成"); }, "thread2"); thread2.start(); }