中断线程

时间:2015-04-02 22:27:55

标签: 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();


         }

1 个答案:

答案 0 :(得分:1)

使用变量例如

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;