2016-10-24 63 views
0

我只是想测试Log.i()并查看android studio中的控制台。在下面的代码onResume应该开始threadrun()应该写在监视器中的标记“运行”层出不穷的“丁”。但运行方法显然只被调用一次。为什么?android线程只运行一次

public class MainActivity extends Activity implements Runnable { 
    Thread gameThread = null; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     Log.i("onCreate","getting started"); 
    } 

    public void run() { 
     Log.i("run","ding"); 
    } 

    @Override 
    public void onResume() { 
     super.onResume(); 
     gameThread = new Thread(this); 
     gameThread.start(); 
    } 
} 

回答

1

您错过了线程究竟做了什么的概念。它允许您异步运行一个工作单元。所以,所有相同的正常规则都适用。它只运行一次的原因是因为线程在run()返回后退出。所以就像任何其他方法,你应该把类似

while(true) 
{ 
    Log.i("run","ding"); 
} 

run()内。理想情况下,你会实际检查一些条件,以便可以根据需要退出线程。

最后,您的MainActivity实施Runnable可能是一个坏主意。通常由其自己的类实现一个线程是很好的风格,例如DingThread implements Runnable

1

你错过了while循环,为什么它只运行一次。使用下面的代码。这是使用线程概念的更好方法。

public class MainActivity extends Activity { 
    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 
     Log.i("onCreate","getting started"); 
    } 

    @Override 
    public void onResume() { 
     super.onResume(); 
     startThread();// create thread obj and start 
    } 

    private GameThread mGameThread = null; 
    private void startThread() { 
     stopThread();// if thread already running stop it then create new thread and start (for avoiding multi-threading). 
     mGameThread = new GameThread(); 
     mGameThread.start();//start the thread. 
    } 

    //To stop the thread simply call this method. 
    private void stopThread() { 
     if(mGameThread != null) { 
      mGameThread.setStop(); 
      mGameThread = null; 
     } 
    } 

    private class GameThread extends Thread { 
     private boolean mIsStop;// mIsStop is default false 

     @Override 
     public void run() { 
      while (!mIsStop) { // if mIsStop is false then only come inside loop. 
       Log.i("run","ding"); //log will print 
      } 
     } 

     public void setStop() { 
      mIsStop = true;// set mIStop variable to true. 
     } 
    } 
}