java线程(四)线程的打断(interrupt)
public void interrupt() //t.interrupt() 打断t线程(设置t线程某给标志位f=true,并不是打断线程的运行)
public boolean isInterrupted() //t.isInterrupted() 查询打断标志位是否被设置(是不是曾经被打断过)
public static boolean interrupted()//Thread.interrupted() 查看“当前”线程是否被打断,如果被打断,恢复标志位
-
-
isInterrupted():实例方法,有没有人打扰我?
-
interrupt和sleep() wait() join()
sleep()方法在睡眠的时候,不到时间是没有办法叫醒的,这个时候可以用interrupt设置标志位,然后呢必须得catch InterruptedException来进行处理,决定继续睡或者是别的逻辑,(自动进行中断标志复位)
public static void main(String[] args) { Thread t = new Thread(()->{ try { Thread.sleep(10000); } catch (InterruptedException e) { System.out.println("Thread is interrupted!"); //抛出InterruptedException异常后,java会自动复位,以免再次被 System.out.println(Thread.currentThread().isInterrupted()); } }); t.start(); SleepHelper.sleepSeconds(5); //设置标志位sleep就会抛出 t.interrupt(); }
public static void main(String[] args) { Thread t = new Thread(()->{ synchronized (o){ try { o.wait(); } catch (InterruptedException e) { System.out.println("Thread is interrupted!"); //抛出InterruptedException异常后,java会自动复位,以免再次被 System.out.println(Thread.currentThread().isInterrupted()); } } }); t.start(); SleepHelper.sleepSeconds(5); t.interrupt(); }
interrupt()不能打断正在竞争锁的线程synchronized()
private static Object o = new Object(); public static void main(String[] args) { Thread t1 = new Thread(()->{ synchronized (o){ SleepHelper.sleepSeconds(10); } }); t1.start(); SleepHelper.sleepSeconds(1); Thread t2 = new Thread(()->{ synchronized (o){ } System.out.println("t2 end"); }); t2.start(); SleepHelper.sleepSeconds(1); t2.interrupt(); }
private static ReentrantLock lock = new ReentrantLock(); public static void main(String[] args) { Thread t1 = new Thread(() -> { lock.lock(); try { Thread.sleep(10000); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } System.out.println("t1 end"); }); t1.start(); SleepHelper.sleepSeconds(1); Thread t2 = new Thread(() -> { System.out.println("t2 start"); try { lock.lockInterruptibly(); } catch (InterruptedException e) { e.printStackTrace(); } finally { lock.unlock(); } System.out.println("t2 end"); }); t2.start(); SleepHelper.sleepSeconds(1); t2.interrupt(); }
多线程与高并发第二版 06线程的结束。
java零基础后端工程师 07IO流、多线程。