我有一个线程,每秒重复一次动作(射击):
long lasttime;
Creature owner;
public Attacker(Creature actor)
{
super("Attacker - "+actor.getClass().getSimpleName());
lasttime=System.currentTimeMillis();
owner=actor;
owner.lockedon=true;
}
@Override
public void run() {
super.run();
while(!owner.dead && owner.lockedon)
{
List pl=TVS.getGameScreen().projectiles;
synchronized (pl)
{
//here
long curtime=System.currentTimeMillis();
if(curtime-lasttime>1000)
{
owner.attack();
lasttime=curtime;
}
}
}
}
但是当主程序线程减慢时,此线程执行速度比main快,并且相对于主线程,射击变得过于频繁。我该怎么办?
答案 0 :(得分:2)
您正忙着等待,持有可能消耗大量CPU的锁,或者锁定试图使用相同锁的其他线程。我建议像
这样的东西while(!owner.dead && owner.lockedon) {
List pl=TVS.getGameScreen().projectiles;
long curtime=System.currentTimeMillis();
long remaining = 1000 - (curtime-lasttime);
if(remaining <= 0) {
synchronized (pl) { // only lock when needed.
owner.attack();
lasttime=curtime;
}
} else {
// when not doing something useful, give up the CPU to another thread.
Thread.sleep(remaining);
}
}
答案 1 :(得分:0)
我宁愿使用计时器,因为它们更容易维护并且更准确:
Timer shooterTimer = new Timer();
shooterTimer.scheduleAtFixedRate(
new TimerTask() {
@Override
public void run() {
if (!owner.dead && owner.lockedon) {
List pl = TVS.getGameScreen().projectiles;
synchronized (pl) {
onwer.attack();
}
}
}
},
0, // Start the timer now
1000); // Execute the task every second