[英]Interrupt a thread
我正在編寫一個使用語音命令移動玩具車的程序,我正在使用線程同時發送數據,問題是當我使用命令退出功能時,我無法中斷線程,請提供任何幫助。
if(response.equals("stop"))
{
motorLeft = 0;
motorRight =0;
(new Thread(new Runnable()
{@Override
public void run()
{
while (!Thread.interrupted())
try
{
Thread.sleep(1000);
runOnUiThread(new Runnable() // start actions in UI thread
{
@Override
public void run()
{
// displayData(); // this action have to be in UI thread
if(BT_is_connect) bl.sendData(String.valueOf( commandLeft+motorLeft+"\r"+commandRight+motorRight+"\r"));
}
});
}
catch (InterruptedException e)
{
// ooops
}
}
})).start(); // the while thread will start in BG thread
}
else
{
if(response.equals("exit"))
Thread.interrupted();
}
例如使用變量
volatile boolean interrupted = false;
然后使用該變量停止
while (!interrupted)
{
try
{
Thread.sleep(1000);
runOnUiThread(new Runnable() // start actions in UI thread
{
@Override
public void run()
{
// displayData(); // this action have to be in UI thread
if(BT_is_connect) bl.sendData(String.valueOf(commandLeft+motorLeft+"\r"+commandRight+motorRight+"\r"));
}
});
}
catch (InterruptedException e)
{
// ooops
}
}
因此,當您想中斷線程時,只需將被中斷的變量更改為true
interrupted = true;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.