2017-09-21 40 views
0

我怎樣才能阻止新Thread(new Runnable()).run如何停止新主題(新的Runnable())

我在android開發新:d,我需要你的幫助:)

我有這樣的代碼,我想提前:)

+0

查找到['了Thread.interrupt()'](HTTPS創建的Runnable://文檔.oracle.com/javase/7/docs/api/java/lang/Thread.html#interrupt())和['Thread.isInterrupted()'](https://docs.oracle.com/javase/7/文檔/ API /爪哇/郎/ Thread.html#isInterrupted())。 – JimmyB

+2

「我想在執行後停止它」 - 線程的'run()'方法返回後,線程將自動終止。你不必爲此做任何事情。 – JimmyB

回答

0

執行

 new Thread(new Runnable() { 
     @Override public void run() { 
      Log.e("MotionLogger", "SU"); 
      Log.i(TAG, "click " + Thread.currentThread().toString()); 

      try { 
       finalCommandLine.writeBytes(command.toString() + '\n'); 
       finalCommandLine.writeBytes("exit\n"); 
       finalCommandLine.flush(); 
       finalCommandLine.close(); 
       finalSuShell.waitFor(); 
      } catch (IOException e1) { 
       e1.printStackTrace(); 
      } catch (InterruptedException e1) { 
       e1.printStackTrace(); 
      } 
     } 

    }).start(); 

感謝你的情況後停止它,你可以使用了Thread.interrupt

或者這樣創建處理程序,如果你想在UI線程上運行

Handler handler= new Handler(); 

然後像這樣

Runnable runnable= new Runnable() { 
     public void run() { 
      //do your work here 
     } 
    }; 
//start like this 
runnable.run(); 
//stop like this 
handler.removeCallbacks(runnable); 
+0

我想它應該是handler.post(runnable)? – Anonymous

+0

這隻會在UI線程上運行,這不是他問的問題。 – ElDuderino

+0

是的,這將在UI線程上運行。 –