[英]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.