使用interrupt()中断线程
当一个线程运行时,另一个线程可以调用对应的Thread对象的interrupt()方法来中断它,该方法只是在目标线程中设置一个标志,表示它已经被中断,并立即返回。
package com.csdhsm.concurrent; import java.util.concurrent.TimeUnit; /** * @Title: InterruptDemo.java * @Package: com.csdhsm.concurrent * @Description 中断Demo * @author Han * @date 2016-4-18 下午6:55:00 * @version V1.0 */ public class InterruptDemo implements Runnable { @Override public void run() { System.out.println("The thread is runing."); System.out.println("The thread is sleeping."); try { //子线程休眠20秒,等待被打断 TimeUnit.SECONDS.sleep(20); System.out.println("The thread is wake up"); } catch (InterruptedException e) { System.out.println("The thread is interrupted"); } //此处会继续执行下去 System.out.println("The thread is terminal"); } public static void main(String[] args) throws InterruptedException { Thread t = new Thread(new InterruptDemo()); t.start(); System.out.println("The Main is sleeping to wait the thread start!"); //主线程休眠2秒,等待子线程运行 TimeUnit.SECONDS.sleep(2); System.out.println("The thread would be interrupted"); t.interrupt(); } }
结果
特别要注意的是标红的地方:如果只是单纯的调用interrupt()方法,线程并没有实际被中断,会继续往下执行。
使用isInterrupted()方法判断中断状态
可以在Thread对象上调用isInterrupted()方法来检查任何线程的中断状态。这里需要注意:线程一旦被中断,isInterrupted()方法便会返回true,而一旦sleep()方法抛出异常,它将清空中断标志,此时isInterrupted()方法将返回false。
package com.csdhsm.concurrent; import java.util.concurrent.TimeUnit; /** * @Title: InterruptedCheck.java * @Package: com.csdhsm.concurrent * @Description Interrupted 测试 * @author Han * @date 2016-4-18 下午7:44:12 * @version V1.0 */ public class InterruptedCheck { public static void main(String[] args) { Thread t = Thread.currentThread(); System.out.println("Current Thread`s statusA is " + t.isInterrupted()); //自己中断自己~ t.interrupt(); System.out.println("Current Thread`s statusC is " + t.isInterrupted()); System.out.println("Current Thread`s statusB is " + t.isInterrupted()); try { TimeUnit.MILLISECONDS.sleep(100); } catch (InterruptedException e) { System.out.println("Current Thread`s statusD is " + t.isInterrupted()); } System.out.println("Current Thread`s statusE is " + t.isInterrupted()); } }
结果
使用interrupted()方法判断中断状态
可以使用Thread.interrupted()方法来检查当前线程的中断状态(并隐式重置为false)。又由于它是静态方法,因此不能在特定的线程上使用,而只能报告调用它的线程的中断状态,如果线程被中断,而且中断状态尚不清楚,那么,这个方法返回true。与isInterrupted()不同,它将自动重置中断状态为false,第二次调用Thread.interrupted()方法,总是返回false,除非中断了线程。
package com.csdhsm.concurrent; /** * @Title: InterruptedCheck.java * @Package: com.csdhsm.concurrent * @Description Interrupted 测试 * @author Han * @date 2016-4-18 下午7:44:12 * @version V1.0 */ public class InterruptedCheck { public static void main(String[] args) { Thread t = Thread.currentThread(); System.out.println("Current Thread`s statusA is " + t.interrupted()); //自己中断自己~ t.interrupt(); System.out.println("Current Thread`s statusC is " + t.interrupted()); System.out.println("Current Thread`s statusB is " + t.interrupted()); System.out.println("Current Thread`s statusD is " + t.interrupted()); } }
结果
注意看红色的标记
时间: 2024-11-05 15:53:16