2016-10-24 64 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. 
     } 
    } 
}