2013-03-21 63 views
0

我正在遵循一個嚮導來展示如何創建一個Pong遊戲。有一部分,我應該創建一個線程,並調用一個移動球的函數。在android中的線程不按預期方式工作

這是我創建的代碼:

package com.ozadari.pingpong; 

public class PingPongGame extends Thread { 
private Ball gameBall; 
private PingPongView gameView; 

public PingPongGame(Ball theBall,PingPongView mainView) 
{ 
    this.gameBall = theBall; 
    this.gameView = mainView; 
} 

@Override 
public void run() 
{ 
    while(true) 
    { 
     this.gameBall.moveBall(); 
     this.gameView.postInvalidate(); 

     try 
     { 
      PingPongGame.sleep(5); 

     } 
     catch(InterruptedException e) 
     { 

      e.printStackTrace(); 
     } 

    } 
}} 

的線程稱爲正常工作,但是它不打印任何東西。我試圖取消infinte循環並使循環運行100次。等待一段時間後,它會在100次運行後打印到屏幕上,但它不會在中間打印任何內容。

問題是什麼?我該如何解決它?

+1

從您的代碼,沒有什麼應該打印。我也想看到moveBall()。 – tilpner 2013-03-21 12:37:30

+0

你有沒有試過把睡眠時間增加到1000?你能看到變化嗎? – WarrenFaith 2013-03-21 12:38:09

+0

聽起來就像你直接從主線程調用運行方法?確保通過調用start來將線程作爲線程啓動。 – 2013-03-21 12:38:46

回答

1

從您發佈的代碼不確定,但無論如何,你可以使用一個處理程序,並讓它運行每秒一次像這樣(時間更改爲你想要的):

Handler handler = new Handler(); 
final Runnable r = new Runnable() 
{ 
    public void run() 
     { 
      //do your stuff here 
       handler.postDelayed(this, 1000); 
     } 
}; 

handler.postDelayed(r, 1000); 

http://developer.android.com/reference/android/os/Handler.html

您也可以使用普通線程,並在最後調用start。

Thread thread = new Thread() 
{ 
    @Override 
    public void run() { 
     try { 
      while(true) { 
       sleep(1000); 
       handler.post(r); 
      } 
     } catch (InterruptedException e) { 
      e.printStackTrace(); 
     } 
    } 
}; 

thread.start(); 
+0

保羅謝謝你,問題是我calle thread.run(); 而不是thread.start();如你所示! 謝謝! – 2013-03-21 15:00:12

+0

很高興你把它分類:) – Paul 2013-03-21 15:17:35

相關問題