如何捕捉一个InterruptedException?详情请进

Patrick_DK 2002-01-14 10:30:33
小弟写了个程序,想捕捉一个InterruptedException,但是没有实现,请高手帮我改一下,以实现catch(InnterruptedException ie)中的语句

public class SL275 implements Runnable
{
public static void main(String[] args)
{
SL275 s=new SL275();
Thread t=new Thread(s);
t.start();
}

public void run()
{
try
{
Thread.sleep(1000);
Thread.interrupted();
}
catch(InterruptedException ie)
{
System.out.println("catch an interruptedexception");
}
finally
{
System.out.println("Implement Runnable Interface");
}
}
}
...全文
187 8 打赏 收藏 转发到动态 举报
写回复
用AI写文章
8 条回复
切换为时间正序
请发表友善的回复…
发表回复
wangtaoyy 2002-01-15
  • 打赏
  • 举报
回复
interrupted()实际上经常用来判断当前线程是正常结束等待还是被打断
wangtaoyy 2002-01-15
  • 打赏
  • 举报
回复
catch(InterruptedException ie)
{
System.out.println("Catch an interruptedexception");
System.out.println("thread interrupted :" + interrupted() );
}
wangtaoyy 2002-01-15
  • 打赏
  • 举报
回复
InterruptedException 捕获以后interrupted()应该返回true;


wangtaoyy 2002-01-14
  • 打赏
  • 举报
回复
interrupted()是测试当前线程是否被打断
应该调用interrupt();
interrupt使sleep和wait状态的线程从这两个方法中抛出InterruptedException
interrupt应从别的线程调用。

如:

Thread t = new Thread(){
public void run(){
try
{
Thread.sleep(5000);
System.out.println("wake up");
}
catch(InterruptedException ie)
{
System.out.println("interrupted!");
}
}
};



t.start();
try{
Thread.sleep(1000);
}
catch(InterruptedException ie){}
t.interrupt();





caolyf 2002-01-14
  • 打赏
  • 举报
回复
看看
Patrick_DK 2002-01-14
  • 打赏
  • 举报
回复
to 路人甲大哥:

我在看MyNote的时候看到一段话
If interrupt method is invoked on a sleeping thread, the thread moves to ready state. The next time it begins running, it executes the InterruptedException handler.

我的意思是想实现这段话所说的
skyyoung 2002-01-14
  • 打赏
  • 举报
回复
throw new InterruptedException("");
??
Patrick_DK 2002-01-14
  • 打赏
  • 举报
回复
to wangtaoyy(嘉陵江)

根据你的提示我改了程序,可以捕捉到异常了,但是在下面这个程序中,把interrupted()方法放在哪里,会返回true啊?

public class SL275 implements Runnable
{
public static void main(String[] args)
{
SL275 s=new SL275();
Thread t=new Thread(s);
t.start();
t.interrupt();
}

public void run()
{
try
{
System.out.println("Sleep");
Thread.sleep(1000);

}
catch(InterruptedException ie)
{
System.out.println("Catch an interruptedexception");
}
}
}

23,407

社区成员

发帖
与我相关
我的任务
社区描述
Java 非技术区
社区管理员
  • 非技术区社区
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告
暂无公告

试试用AI创作助手写篇文章吧