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

上面注释,第9行到第16行表明,stop()方法可以停止“其他线程”。执行thread.stop()方法这条语句的线程称为当前线程,而“其他线程”则是 调用thread.stop()方法的对象thread所代表的线程。

如:

1 public static void main(String[] args) { 2 MyThread thread = new MyThread... 3 //..... 4 thread.stop(); 5 //.... 6 }

在main方法中,当前线程就是main线程。它执行到第4行,想把“其他线程”thread“ 给停止。这个其他线程就是MyThread类 new 的thread对象所表示的线程。

第21行至23行表明,可以停止一个尚未started(启动)的线程。它的效果是:当该线程启动后,就立马结束了。

第48行以后的注释,则深刻表明了为什么stop()方法被弃用!为什么它是不安全的。

比如说,threadA线程拥有了监视器,这些监视器负责保护某些临界资源,比如说银行的转账的金额。当正在转账过程中,main线程调用 threadA.stop()方法。结果导致监视器被释放,其保护的资源(转账金额)很可能出现不一致性。比如,A账户减少了100,而B账户却没有增加100

二,中断机制

JAVA中如何正确地使用中断机制的细节太多了。interrupted()方法与 isInterrupted()方法都是反映当前线程的是否处于中断状态的。

①interrupted()

1 /** 2 * Tests whether the current thread has been interrupted. The 3 * <i>interrupted status</i> of the thread is cleared by this method. In 4 * other words, if this method were to be called twice in succession, the 5 * second call would return false (unless the current thread were 6 * interrupted again, after the first call had cleared its interrupted 7 * status and before the second call had examined it). 8 * 9 * <p>A thread interruption ignored because a thread was not alive 10 * at the time of the interrupt will be reflected by this method 11 * returning false. 12 * 13 * @return <code>true</code> if the current thread has been interrupted; 14 * <code>false</code> otherwise. 15 * @see #isInterrupted() 16 * @revised 6.0 17 */ 18 public static boolean interrupted() { 19 return currentThread().isInterrupted(true); 20 }

从源码的注释中看出,它测试的是当前线程(current thread)的中断状态,且这个方法会清除中断状态。

②isInterrupted()

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

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