2017-09-21 42 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线程上运行。 –