2015-04-02 89 views
0

我正在編寫一個程序來使用語音命令移動玩具車我正在使用線程同時發送數據問題是,當我使用命令退出時,我無法中斷我的線程請任何幫助。中斷一個線程

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

使用例如可變

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; 
+1

** volatile **布爾中斷 – 2015-04-03 01:35:09