[英]Thread in android not working as expected
我正在遵循一個指南,該指南顯示了如何創建Pong游戲。 有一部分,我應該創建一個線程,並調用一個使球移動的函數。
這是我創建的代碼:
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();
}
}
}}
該線程被調用並且可以正常工作,但它不會輸出任何內容。 我試圖取消無限循環,並使循環運行100次。 我稍等片刻后,它會像運行100次后一樣顯示在屏幕上,但中間不會打印任何內容。
問題是什么? 我該如何解決?
不確定已發布的代碼,但無論如何,您可以使用處理程序並使其每秒運行一次,如下所示(將時間更改為所需的時間):
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();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.