作者LaPass (LaPass)
看板java
标题Re: [问题] 如何中断跑到一半的程式
时间Wed Aug 29 14:30:19 2012
以下范例徒手key的,可能会打错字,以及少做try...catch之类的
请自已修正
法一:
Thread + 设个flag去判断
class UI{
...
....
Thread t;
boolean b=true;
public void StartButton(){
t=new Thread(new Runnable(){
void run(){
while(b)
{
//要做的一些事情
}
}
});
}
public void StopButton(){
b=false;
}
}
这种方法比较好,有些东西做到一半被停掉的话会很麻烦
用flag的方式比较能让程式自己决定该不该中止,以及把一些该收尾的事情做一做
但这也只适用於回圈类型的程式
法二:
class UI{
...
....
Thread t;
public void StartButton(){
t=new Thread(new Runnable(){
void run(){
//要做的一些事情
}
});
}
public void StopButton(){
if(t!=null)t.interrupt();
}
}
用interrupt去中断他
但是,印象中如果有像这样的片段
try { }
finally { }
会直接被中断掉,而不会去做finally的动作去收尾
还有,如果是第一次使用执行绪的话
请去看一下关於执行绪安全之类的问题、文章
--
--
※ 发信站: 批踢踢实业坊(ptt.cc)
◆ From: 61.59.16.65
1F:→ byend:呼叫 interrupt() 只是把 interrupt flag 设成 True 08/29 14:31
2F:推 f0987654:感谢,我会在试试 08/29 14:41