java线程中断是一种线程间的协作模式,通过设置线程的中断标志并不能直接终止该线程的运行,而是被中断的线程根据中断状态自行处理。
package com.heiye.learn1; import java.util.logging.Logger; public class InterruptedTest { public static void main(String[] args) throws InterruptedException { Logger logger=Logger.getLogger(InterruptedTest.class.toString()); Thread thread=new Thread(new Runnable() { @Override public void run() { //如果当前线程被中断则退出循环 while (!Thread.currentThread().isInterrupted()){ logger.warning(Thread.currentThread()+"Hello"); } } }); //启动子线程 thread.start(); //主线程休眠1s,以便中断当前让子线程输出 Thread.sleep(1000); //中断子线程 logger.warning("main thread interrupted thread"); thread.interrupt(); //等待子线程执行完毕 thread.join(); logger.info("main is over"); } }
在如上代码中,子线程thread通过检查当前线程中断标志来控制是否退出循环,主线程在休眠1s后调用了thread的interupted()方法设置了中断标志,所以线程thread退出了循环。
下面看一种情况,当线程为了等待一些特定条件的到来时候,一般会使用sleep()方法,wait(),join()方法来阻塞挂起当前线程。下面看一个例子:
package com.heiye.learn1; import java.util.logging.Logger; public class InterruptedTest2 { public static void main(String[] args) throws InterruptedException { Logger logger = Logger.getLogger(InterruptedTest.class.toString()); Thread threadOne = new Thread(new Runnable() { @Override public void run() { logger.info("threadOne begin sleep 2000 seconds"); try { Thread.sleep(2000000); logger.info("threadOne awaking"); } catch (InterruptedException e) { logger.warning("threadOne is interrupted while sleeping"); return; //e.printStackTrace(); } logger.warning("threadOne-leaving normally") ; } }); threadOne.start(); //确保子线程进入睡眠状态 Thread.sleep(1000); //打断子线程睡眠,让子线程从sleep返回 threadOne.interrupt(); //等待子线程执行完毕 threadOne.join(); logger.info("main thread is over"); } }