我正在遵循一个展示如何创建 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();
关于java - Android 中的线程未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15547681/