JAVA多线程之中断机制stop()、interrupted()、isInterrupted()
一,介绍
本文记录JAVA多线程中的中断机制的一些知识点。主要是stop方法、interrupted()与isInterrupted()方法的区别,并从源代码的实现上进行简单分析。
JAVA中有3种方式可以终止正在运行的线程
①线程正常退出,即run()方法执行完毕了
②使用Thread类中的stop()方法强行终止线程。但stop()方法已经过期了,不推荐使用
③使用中断机制
线程正常退出没有什么东东,中断机制下面详细介绍,先看下stop()方法的源代码,关键是源代码上的注释。它解释了为什么stop()不安全,stop()方法停止的是哪个线程?
/** *Forcesthethreadtostopexecuting. *<p> *Ifthereisasecuritymanagerinstalled,its<code>checkAccess</code> *methodiscalledwith<code>this</code> *asitsargument.Thismayresultina *<code>SecurityException</code>beingraised(inthecurrentthread). *<p> *Ifthisthreadisdifferentfromthecurrentthread(thatis,thecurrent *threadistryingtostopathreadotherthanitself),the *securitymanager's<code>checkPermission</code>method(witha *<code>RuntimePermission("stopThread")</code>argument)iscalledin *addition. *Again,thismayresultinthrowinga *<code>SecurityException</code>(inthecurrentthread). *<p> *Thethreadrepresentedbythisthreadisforcedtostopwhatever *itisdoingabnormallyandtothrowanewlycreated *<code>ThreadDeath</code>objectasanexception. *<p> *Itispermittedtostopathreadthathasnotyetbeenstarted. *Ifthethreadiseventuallystarted,itimmediatelyterminates. *<p> *Anapplicationshouldnotnormallytrytocatch *<code>ThreadDeath</code>unlessitmustdosomeextraordinary *cleanupoperation(notethatthethrowingof *<code>ThreadDeath</code>causes<code>finally</code>clausesof *<code>try</code>statementstobeexecutedbeforethethread *officiallydies).Ifa<code>catch</code>clausecatchesa *<code>ThreadDeath</code>object,itisimportanttorethrowthe *objectsothatthethreadactuallydies. *<p> *Thetop-levelerrorhandlerthatreactstootherwiseuncaught *exceptionsdoesnotprintoutamessageorotherwisenotifythe *applicationiftheuncaughtexceptionisaninstanceof *<code>ThreadDeath</code>. * *@exceptionSecurityExceptionifthecurrentthreadcannot *modifythisthread. *@see#interrupt() *@see#checkAccess() *@see#run() *@see#start() *@seeThreadDeath *@seeThreadGroup#uncaughtException(Thread,Throwable) *@seeSecurityManager#checkAccess(Thread) *@seeSecurityManager#checkPermission *@deprecatedThismethodisinherentlyunsafe.Stoppingathreadwith *Thread.stopcausesittounlockallofthemonitorsthatit *haslocked(asanaturalconsequenceoftheunchecked *<code>ThreadDeath</code>exceptionpropagatingupthestack).If *anyoftheobjectspreviouslyprotectedbythesemonitorswerein *aninconsistentstate,thedamagedobjectsbecomevisibleto *otherthreads,potentiallyresultinginarbitrarybehavior.Many *usesof<code>stop</code>shouldbereplacedbycodethatsimply *modifiessomevariabletoindicatethatthetargetthreadshould *stoprunning.Thetargetthreadshouldcheckthisvariable *regularly,andreturnfromitsrunmethodinanorderlyfashion *ifthevariableindicatesthatitistostoprunning.Ifthe *targetthreadwaitsforlongperiods(onaconditionvariable, *forexample),the<code>interrupt</code>methodshouldbeusedto *interruptthewait. *Formoreinformation,see *<ahref="{@docRoot}/../technotes/guides/concurrency/threadPrimitiveDeprecation.html">Why *areThread.stop,Thread.suspendandThread.resumeDeprecated?</a>. */ @Deprecated publicfinalvoidstop(){ stop(newThreadDeath()); }
上面注释,第9行到第16行表明,stop()方法可以停止“其他线程”。执行thread.stop()方法这条语句的线程称为当前线程,而“其他线程”则是调用thread.stop()方法的对象thread所代表的线程。
如:
publicstaticvoidmain(String[]args){ MyThreadthread=newMyThread... //..... thread.stop(); //.... }
在main方法中,当前线程就是main线程。它执行到第4行,想把“其他线程”thread“给停止。这个其他线程就是MyThread类new的thread对象所表示的线程。
第21行至23行表明,可以停止一个尚未started(启动)的线程。它的效果是:当该线程启动后,就立马结束了。
第48行以后的注释,则深刻表明了为什么stop()方法被弃用!为什么它是不安全的。
比如说,threadA线程拥有了监视器,这些监视器负责保护某些临界资源,比如说银行的转账的金额。当正在转账过程中,main线程调用threadA.stop()方法。结果导致监视器被释放,其保护的资源(转账金额)很可能出现不一致性。比如,A账户减少了100,而B账户却没有增加100
二,中断机制
JAVA中如何正确地使用中断机制的细节太多了。interrupted()方法与isInterrupted()方法都是反映当前线程的是否处于中断状态的。
①interrupted()
/** *Testswhetherthecurrentthreadhasbeeninterrupted.The *<i>interruptedstatus</i>ofthethreadisclearedbythismethod.In *otherwords,ifthismethodweretobecalledtwiceinsuccession,the *secondcallwouldreturnfalse(unlessthecurrentthreadwere *interruptedagain,afterthefirstcallhadcleareditsinterrupted *statusandbeforethesecondcallhadexaminedit). * *<p>Athreadinterruptionignoredbecauseathreadwasnotalive *atthetimeoftheinterruptwillbereflectedbythismethod *returningfalse. * *@return<code>true</code>ifthecurrentthreadhasbeeninterrupted; *<code>false</code>otherwise. *@see#isInterrupted() *@revised. */ publicstaticbooleaninterrupted(){ returncurrentThread().isInterrupted(true); }
从源码的注释中看出,它测试的是当前线程(currentthread)的中断状态,且这个方法会清除中断状态。
②isInterrupted()
/** *Testswhetherthisthreadhasbeeninterrupted.The<i>interrupted *status</i>ofthethreadisunaffectedbythismethod. * *<p>Athreadinterruptionignoredbecauseathreadwasnotalive *atthetimeoftheinterruptwillbereflectedbythismethod *returningfalse. * *@return<code>true</code>ifthisthreadhasbeeninterrupted; *<code>false</code>otherwise. *@see#interrupted() *@revised. */ publicbooleanisInterrupted(){ returnisInterrupted(false); }
从源码注释中可以看出,isInterrupted()方法不会清除中断状态。
③interrupted()方法与isInterrupted()方法的区别
从源代码可以看出,这两个方法都是调用的isInterrupted(booleanClearInterrupted),只不过一个带的参数是true,另一个带的参数是false。
/** *TestsifsomeThreadhasbeeninterrupted.Theinterruptedstate *isresetornotbasedonthevalueofClearInterruptedthatis *passed. */ privatenativebooleanisInterrupted(booleanClearInterrupted);
因此,第一个区别就是,一个会清除中断标识位,另一个不会清除中断标识位。
再分析源码,就可以看出第二个区别在return语句上:
publicstaticbooleaninterrupted(){ returncurrentThread().isInterrupted(true); } /************************/ publicbooleanisInterrupted(){ returnisInterrupted(false); }
interrupted()测试的是当前的线程的中断状态。而isInterrupted()测试的是调用该方法的对象所表示的线程。一个是静态方法(它测试的是当前线程的中断状态),一个是实例方法(它测试的是实例对象所表示的线程的中断状态)。
下面用个具体的例子来更进一步地阐明这个区别。
有一个自定义的线程类如下:
publicclassMyThreadextendsThread{ @Override publicvoidrun(){ super.run(); for(inti=;i<;i++){ System.out.println("i="+(i+)); } } }
先看interrupted()方法的示例:
publicclassRun{ publicstaticvoidmain(String[]args){ try{ MyThreadthread=newMyThread(); thread.start(); Thread.sleep(); thread.interrupt(); //Thread.currentThread().interrupt(); System.out.println("是否停止?="+thread.interrupted());//false System.out.println("是否停止?="+thread.interrupted());//falsemain线程没有被中断!!! //......
第5行启动thread线程,第6行使main线程睡眠1秒钟从而使得thread线程有机会获得CPU执行。
main线程睡眠1s钟后,恢复执行到第7行,请求中断thread线程。
第9行测试线程是否处于中断状态,这里测试的是哪个线程呢???答案是main线程。因为:
(1)interrupted()测试的是当前的线程的中断状态
(2)main线程执行了第9行语句,故main线程是当前线程
再看isInterrupted()方法的示例:
publicclassRun{ publicstaticvoidmain(String[]args){ try{ MyThreadthread=newMyThread(); thread.start(); Thread.sleep(); thread.interrupt(); System.out.println("是否停止?="+thread.isInterrupted());//true
在第8行,是thread对象调用的isInterrupted()方法。因此,测试的是thread对象所代表的线程的中断状态。由于在第7行,main线程请求中断thread线程,故在第8行的结果为:true