Java多线程之中断机制(stop()、interrupted()、isInt(3)

1 /** 2 * Tests whether this thread has been interrupted. The <i>interrupted 3 * status</i> of the thread is unaffected by this method. 4 * 5 * <p>A thread interruption ignored because a thread was not alive 6 * at the time of the interrupt will be reflected by this method 7 * returning false. 8 * 9 * @return <code>true</code> if this thread has been interrupted; 10 * <code>false</code> otherwise. 11 * @see #interrupted() 12 * @revised 6.0 13 */ 14 public boolean isInterrupted() { 15 return isInterrupted(false); 16 }

从源码注释中可以看出,isInterrupted()方法不会清除中断状态。

③interrupted()方法与 isInterrupted()方法的区别

从源代码可以看出,这两个方法都是调用的isInterrupted(boolean ClearInterrupted),只不过一个带的参数是true,另一个带的参数是false。

1 /** 2 * Tests if some Thread has been interrupted. The interrupted state 3 * is reset or not based on the value of ClearInterrupted that is 4 * passed. 5 */ 6 private native boolean isInterrupted(boolean ClearInterrupted);

因此,第一个区别就是,一个会清除中断标识位,另一个不会清除中断标识位。

再分析源码,就可以看出第二个区别在return 语句上:

public static boolean interrupted() { return currentThread().isInterrupted(true); } /************************/ public boolean isInterrupted() { return isInterrupted(false); }

interrupted()测试的是当前的线程的中断状态。而isInterrupted()测试的是调用该方法的对象所表示的线程。一个是静态方法(它测试的是当前线程的中断状态),一个是实例方法(它测试的是实例对象所表示的线程的中断状态)。

下面用个具体的例子来更进一步地阐明这个区别。

有一个自定义的线程类如下:

1 public class MyThread extends Thread { 2 @Override 3 public void run() { 4 super.run(); 5 for (int i = 0; i < 500000; i++) { 6 System.out.println("i=" + (i + 1)); 7 } 8 } 9

先看interrupted()方法的示例:

1 public class Run { 2 public static void main(String[] args) { 3 try { 4 MyThread thread = new MyThread(); 5 thread.start(); 6 Thread.sleep(1000); 7 thread.interrupt(); 8 //Thread.currentThread().interrupt(); 9 System.out.println("是否停止1?="+thread.interrupted());//false 10 System.out.println("是否停止2?="+thread.interrupted());//false main线程没有被中断!!!
      //......

第5行启动thread线程,第6行使main线程睡眠1秒钟从而使得thread线程有机会获得CPU执行。

main线程睡眠1s钟后,恢复执行到第7行,请求中断 thread线程。

第9行测试线程是否处于中断状态,这里测试的是哪个线程呢???答案是main线程。因为:

(1)interrupted()测试的是当前的线程的中断状态

(2)main线程执行了第9行语句,故main线程是当前线程

再看isInterrupted()方法的示例:

1 public class Run3 { 2 public static void main(String[] args) { 3 try { 4 MyThread thread = new MyThread(); 5 thread.start(); 6 Thread.sleep(1000); 7 thread.interrupt(); 8 System.out.println("是否停止1?="+thread.isInterrupted());//true

内容版权声明:除非注明,否则皆为本站原创文章。

转载注明出处:https://www.heiqu.com/f4396d814474e76c2952dafb2e2f8fc1.html