java - 如何仅延迟特定方法?
问题描述
我仍然是一个非常早期的编码员,并且仍然不了解有关 java 的一切,所以我的代码仍然有点混乱,对此感到抱歉。我正在用图形 g 类制作一个简单的平台游戏,我试图弄清楚如何在不暂停整个脚本的情况下延迟方法。
我已经尝试过 Thread.sleep() 和 TimeUnit.SECONDS.sleep() 但这两个都冻结了当时运行的其他方法,以及保持游戏运行的 Timer。
private static Timer timer;
private int delay = 10;
public Gameplay() {
addKeyListener(this);
setFocusable(true);
setFocusTraversalKeysEnabled(false);
timer = new Timer(delay, this);
timer.start();
}
public void moveDown() {
if (play == true) {
Playsound("drop");
dropping = true;
//pause here for 1 second without freezing timer or other running methods
dropping = false;
}
}
我希望程序在等待时继续运行,但我尝试过的东西总是冻结整个程序
解决方案
我身边的一招
public void moveDown() {
if (play == true) {
Playsound("drop");
dropping = true;
//create a thread which will execute your method and set sleep on that thread
dropping = false;
}
推荐阅读
- flutter - 如何在没有 android studio 模拟器的情况下在 VSCode 中运行颤振应用程序
- php - 如何在php中使用firebase发送带有图像和徽章的推送通知?
- python - python子进程通配符仅选择第一个文件
- php - 如何使用 PHP 从直接 URL 下载设备上的图像?
- mysql - Mysql EXECUTE 使用 null ...?
- angular - URL 已更改,但未呈现组件。重新加载页面后才能正常工作
- pandas - 更改 Excel 日期(作为整数)与单列中的时间戳混合 - 尝试过 str.extract
- reactjs - 带有反应路由器的新页面的位置
- python - Openweathemap API 说温度就像 282
- reactjs - React Router ^6.0.0-beta.0 历史道具删除 - 在反应上下文之外导航