如何捕捉一个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");
}
}
}
...全文
183 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");
}
}
}
内容概要:本文围绕高比例可再生能源并网背景下虚拟电厂的多时间尺度调度问题展开研究,重点解决系统灵活性与储能成本之间的平衡挑战。通过构建日前调度与日内调度的双层优化模型,整合风电、光伏等不确定性出力与多用户负荷的灵活性资源,同时引入储能系统容量衰减模型,提升调度方案的经济性与可持续性。研究采用Matlab行仿真验证,实现了对储能充放电行为的精细化管理,并结合先优化算法求解非线性约束下的复杂调度问题,有效降低了系统运行成本,增强了电网对可再生能源的消纳能力。; 适合人群:具备电力系统、可再生能源或优化调度基础知识的研究生、科研人员及工程技术人员,熟悉Matlab编程与数学建模者更佳; 使用场景及目标:①用于高比【顶级SCI复现】高比例可再生能源并网如何平衡灵活性与储能成本?虚拟电厂多时间尺度调度及衰减建模(Matlab代码实现)例新能源接入场景下的虚拟电厂能量管理系统设计;②支撑含储能系统的多时间尺度调度策略研究,提升调度精度与设备寿命;③为SCI论文复现与科研课题提供可扩展的技术框架与代码基础; 阅读建议:建议结合文中提到的Matlab代码实现部分,逐步运行并理解模型构建、约束设定与求解流程,重点关注储能衰减建模与灵活性资源协调机制的设计思路,宜配合YALMIP、CPLEX等工具包行调试与优化。

23,407

社区成员

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

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