目录
interrupt方法
interrupt方法:结束线程在调用Object类的wait方法或该类的join方法、sleep方法过程中的阻塞状态,并在调用wait、join和sleep方法处产生InterruptedException异常。
public class Pool { public static void main(String[] args) { Thread thread = new Thread(new Timeo()); thread.start(); try { Thread.sleep(20000); } catch (InterruptedException e) { e.printStackTrace(); } thread.interrupt();//调用interrupt方法的线程结束阻塞 } } class Timeo implements Runnable{ @Override public void run() { System.out.println(new Date()); try { Thread.sleep(30000); } catch (InterruptedException e) { e.printStackTrace(); } System.out.println("++++++++++++++++++"); } }
结果显示如下:
当执行主线程发生阻塞20s,然后执行时间线程,当执行到sleep(30000);时,线程发生阻塞30s,此时主线程和时间线程都发生阻塞,主线程thread.interrupt(); 结束阻塞,产生InterruptedException异常