java - 中断一个线程

标签 java android multithreading

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

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/

相关文章:

java - HashSet、HashMap等中如何进行值比较

java - File.list() 与 File.listFiles()

java - 如何防止线程在条件暂时不满足时被终止?

java - Java线程依赖

java - 如果任务遇到异常,则会抑制其进一步执行。为什么?

Java 8 Nashorn - 将 engine.eval ("print(' hello world')) 捕获到 String 对象中?

java - 以更具可读性的方式在 ArrayList 中添加元素

Android ViewFlow setFlowIndicator IndexOutOfBoundException 异常

android - Eclipse:Android 项目中 JDK 类的 java.lang.NoClassDefFoundError

Java 将 .obj 转换为适用于 Android 的 OpenGL