我正在编写一个使用语音命令移动玩具车的程序,我正在使用线程同时发送数据,问题是当我使用命令退出功能时,我无法中断我的线程,请提供任何帮助。
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;
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句