package com.subject01; public class InterruptDemo { public static void main(String[] args) { SimpleThread st = new SimpleThread(); Thread t = new Thread(st); t.start(); try { Thread.sleep(2000); }catch(InterruptedException e){ e.printStackTrace(); } System.out.println("in main() - interrupting other thread"); //中断线程t // 如果只是单纯的调用interrupt,线程并没有真正的终止,可搭配return进行使用 t.interrupt(); System.out.println("in main() - leaving"); System.out.println("================================"); System.out.println("测试isInterrupt:"); testIsinterrupt(); } public static void testIsinterrupt(){ Thread t = Thread.currentThread(); // isInterrupted() 判断线程是否被中止,如果被中止则返回true,否则则范围false ; System.out.println("A当前线程是否被中止:"+t.isInterrupted()); t.interrupt(); System.out.println("B当前线程是否被中止:"+t.isInterrupted()); // 如果Thread.sleep()抛出异常,则会清除中止标识 try { Thread.sleep(2000); } catch (InterruptedException e) { System.out.println("C当前线程是否被中止:"+t.isInterrupted()); } System.out.println("D当前线程是否被中止:"+t.isInterrupted()); } } class SimpleThread implements Runnable{ @Override public void run() { try { System.out.println("in run() - about to sleep for 20 seconds"); Thread.sleep(20000); System.out.println("in run() - woke up"); } catch (InterruptedException e) { System.out.println("in run() - interrupted while sleeping"); //如果没有return,线程不会实际被中断,它会继续打印下面的信息 return ; } System.out.println("in run() - leaving normally"); } }
http://blog.csdn.net/ns_code/article/details/17091267
时间: 2024-10-09 21:25:04