gpt4 book ai didi

java - 中断一个线程

转载 作者:行者123 更新时间:2023-12-01 11:42:24 25 4
gpt4 key购买 nike

我正在编写一个程序来使用语音命令移动玩具车我正在使用线程同时发送数据,问题是当我使用命令退出时我无法中断我的线程,请提供帮助。

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
}
}

因此,当您想中断线程时,只需将 interrupted 变量更改为 true

interrupted = true;

关于java - 中断一个线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29423527/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com