我已經在這幾個小時內與此戰鬥了。下面的代碼:如何中斷一個無限循環的線程和Java睡眠
@Override
public void run()
{
try
{
wscript.setBid(0.30);
wscript.setServiceMode(WebScript.ServiceMode.ON);
for(;!Thread.currentThread().isInterrupted();)
{
Positioning(demandedPosition, maximumBid);
if(Thread.currentThread().isInterrupted())
break;
Thread.sleep(10000);
}
wscript.setServiceMode(ServiceMode.OFF);
Log("Algorithm has been canceled!");
}
catch (InterruptedException e)
{
wscript.setServiceMode(ServiceMode.OFF);
Log("Algorithm has been canceled!");
return;
}
的事情是,我想使用此代碼中斷它在合法的方式:
private void StopService()
{
service.interrupt();
}
當我把這種方法時Thread.sleep()方法正在運行,它得到InterruptedException並且一切正常。然而,正如我在PositioningAlgorithm運行時所稱的那樣,線程沒有發生任何事情,線程的行爲就像它從未得到中斷狀態。 Regards, DualCore
編輯:這對我來說是必不可少的通話記錄(「算法已被取消!」);將在中斷後執行。
解決:我已經覆蓋Thread.interrupt()
編輯這是檢查線程是否準備結束類的局部變量:
service = new Thread(mechanism)
{
@Override
public void interrupt()
{
super.interrupt();
mechanism.ReadyToReturn = true;
}
};
,這裏是更新線程的主要算法:
@Override
public void run()
{
try
{
wscript.setBid(0.30);
wscript.setServiceMode(WebScript.ServiceMode.ON);
for(;!ReadyToReturn || !Thread.currentThread().isInterrupted();)
{
Positioning(demandedPosition, maximumBid);
if(ReadyToReturn || Thread.currentThread().isInterrupted())
break;
Thread.sleep(10000);
}
wscript.setServiceMode(ServiceMode.OFF);
Log("Algorithm has been canceled!");
}
catch (InterruptedException e)
{
wscript.setServiceMode(ServiceMode.OFF);
Log("Algorithm has been canceled!");
return;
}
}
您的意思是說,當您調用service.interrupt時,Positioning()不會立即退出?或者,如果(Thread.currentThread()。isInterrupted())的條件不成立,如果調用service.interrupt和Positioning()返回? –
Positioning()不會立即退出,當我調用它並且在Positioning()返回後條件不成立時。 – DualCore
那麼,如果正在進行一些工作,'Positioning()'方法不會立即退出。但是,你期望至少能夠設置「中斷」標誌是正確的。你能告訴我們'Positioning()'方法的內容嗎?否則,JiriS的回答聽起來是正確的。 – sstan