新闻正文

关于JAVA多线程编程中的interrupt()调用

来源:JAVA天堂  JAVA学习者  2007-5-15 02:06:25 网友评论 0 条 字体:[ ] ~我要投稿!
, 站内信件
是关于interrupt()调用的,以下程序引自一本多线程编程的书,
书中提到了重复中断,原文如下:读者会避免处理InterruptedException
,在这种情况,可以设置一个标志,重新进入所运行的代码,一直等待
到该代码正常返回,然后在离开前自己调用中断。(该标志就是interrupted)
public void condWait(Mutex mutex) {
boolean interrupted = false;
while(true){
try{
synchronized (this) {
mutex.unlock();
wait();
}
catch (InterruptedException ie) {interrupted=true;}
}
mutex.lock();
if (interrupted) Thread.currentThread().interrupt();
}
在调用上面的程序时,有如下程序:
public void readLock() {
m.lock();
while(!condition)
condWait(m);
m.unlock();
}
调用以上程序的时候,会造成condWait重复调用
如果改用:
public void readLock() {
boolean interrupted = false;
m.lock();
while(!condition) {
condWait(m);
if(Thread.interrupted()) interrupted =true;
}
m.unlock();
if (interrupted) Thread.currentThread().interrupt();
}
那么:interrupt()函数调用时,按照JDK函数参考,是置位中断标志,
并使目的线程抛出一个InterruptedException,这里目的线程是否是
立即中止从而进入异常处理块,还是完全按照上面所说,只是把中断
标志置位?究竟为何第二个程序可以避免condWait()的重复调用,从而
推出while循环?此外,在condWait()的实现中,如果线程被interrupt,
那么按照JDK的描述,该进入catch块,可是catch块只是设置了interrupted
变量,并没有进行任何处置,而程序尚在while(true)块当中,难道还
会继续循环继续wait()吗?偶对此不理解,哪位可以诠释一番,谢谢!


收藏到ViVi   收藏此页到365Key
上一篇: Re: 如何反编译
下一篇: Sun推出Java Web Services Developer Pack (WSDP)
用户名:新注册) 密码: 匿名评论 [所有评论]
评论内容:不能超过250字,需审核后才会公布,请自觉遵守互联网相关政策法规。
本栏搜索
  • Google
   网站首页 -  网站地图 -  技术学习 -  网站投稿 -  帮助中心
Copyright 2003-2008 www.javah.net All Rights Reserved
2008 如果你喜欢本站 请收藏本站 并推荐给你的朋友一起分享