我有一个程序(一个 AWT 框架,是的,我知道 Swing 更好,但我被限制使用它)有 2 个移动对象。所以我想我会把每个都放在自己的线程中,以允许对象以不同的速度移动,等等。
一个线程 ( gameThread
) 处理弹跳球,另一个线程 ( ) 处理cannonThread
画在屏幕上的大炮和它发射的弹丸。我不确定如何区分球的速度和弹丸的速度,这就是为什么我认为 2 个线程可以工作(通过使用thread.sleep(speedofobject)
)。
我不知道如何实现它们,而且我的随机猜测(显然)没有用。屏幕上什么也没有显示,编译时也没有产生错误。以前,球会出现在屏幕上并按应有的方式移动。
这是我尝试执行多个线程的片段。如果您需要更多信息,请告诉我,我会发布。
public void start()
{
if (gameThread == null)
{
gameThread = new Thread(this);
gameThread.start();
}
if (cannonThread == null)
{
cannonThread = new Thread(this);
cannonThread.start();
}
}
public void run()
{
//thread for the ball, collision detection and scorekeeping
if (Thread.currentThread().equals(gameThread))
{
Thread.currentThread().setPriority(Thread.MAX_PRIORITY);
while (!kill)
{
if (!paused)
{
target.repaint();
}
try
{
Thread.sleep(ballSpeed);
}
catch(InterruptedException e){System.err.println("Interrupted.");}
}
stop();
}
//thread for the cannon and projectile
if (Thread.currentThread().equals(cannonThread))
{
Thread.currentThread().setPriority(Thread.NORM_PRIORITY);
if (!paused)
{
if (projectileFiring)
{
cannon.repaint();
}
try
{
Thread.sleep(projectileSpeed);
}
catch(InterruptedException e){System.err.println("Interrupted.");}
}
}
}