gpt4 book ai didi

java - 尝试 thread.sleep 代码的一部分,但它会影响整个事情

转载 作者:行者123 更新时间:2023-11-29 04:22:14 24 4
gpt4 key购买 nike

我正在尝试让角色移动以进行攻击,然后在攻击发生后返回。我尝试在之前的第一步中执行 thread.sleep,然后是攻击并在之后返回,但它只会影响整个代码,就好像它在一切之前而不是在中间。

我检查了很多类似的问题,但没有一个适用于或适用于我正在寻找的内容。

JButton btnAttack = new JButton("Attack");
btnAttack.addActionListener(new ActionListener() {
int theehp = currentehp;
int yourhp = maxhp;

public void actionPerformed(ActionEvent arg0) {
int damage = 0;
//moves to sleep
label.move(300, 50);

damage = (int) (Math.random()* 4 + 1);
theehp = theehp - damage;
ehplbl.setText(String.valueOf(theehp));
ehp.setValue(theehp);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//moves back
label.move(39,46);

if (theehp <= 0){
combat.this.setVisible(false);
clip.close();
JOptionPane.showMessageDialog(panel, "You win!");

}else{
damage = (int) (Math.random()* 2 + 1);
yourhp = yourhp - damage;
hp.setValue(yourhp);
lblhp.setText(String.valueOf(yourhp));}
if (yourhp <=0){
combat.this.setVisible(false);
clip.close();
JOptionPane.showMessageDialog(panel, "You lose!");

}
};
});
btnAttack.setBounds(39, 393, 108, 61);
panel.add(btnAttack);

最佳答案

Thread.sleep() 将真正停止当前线程在这段时间内运行任何东西。

如果您希望在该线程 hibernate 的同时完成其他工作,则必须将该工作放在另一个线程上。研究 Executors 和类似的东西,看看如何创建多个线程并正确管理它们。

请注意,除非您有 2 个以上的线程在运行,否则您的程序一次只会做一件事(至少在业务逻辑方面,JVM 在其自己的线程上在后台做很多事情)。

关于java - 尝试 thread.sleep 代码的一部分,但它会影响整个事情,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48386566/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com