Java异步等待x秒

问题描述 投票:0回答:2

给出一些关于我正在尝试做的事情的细节:我正在用 Java 制作一个 Minecraft 插件。我有一个对象,它使用 HashMap 绑定到 Minecraft 的 Player 对象。

我在这个对象中有一个方法,类似于:

    public void faint() {
        ... //Apply the effect on the player

        //wait for x seconds, and if the player didn't already wake up, wake them up. (player.wakeUp())
    }

显然,会有很多事情发生,所以我希望这是异步发生的。计时器将在后台继续运行,并且不会阻止代码中的其他任何内容。

抱歉,如果我的问题太简单了,但我确实查过网络,而且我是Java新手,所以请原谅我的无知。

java minecraft bukkit
2个回答
0
投票

使用 Bukkit 调度程序

Bukkit.getScheduler().runTaskLater(yourPluginInstance, () -> {
    // put code here to run after the delay
}, delayInTicks);

当代码在延迟后运行时,它将在主服务器线程上运行。


0
投票

您可以通过实现这样的

Runnable
接口来创建一个单独的线程,并在其中进行延迟。

// This is happening in the main thread
Thread thread = new Thread(){
    public void run(){
      // This code will run async after you execute
      // thead.start() below
      try {
        Thread.sleep(1000);
        System.out.println("Time to wake up");
      } catch (InterruptedException e) {
        // See https://www.javaspecialists.eu/archive/Issue056-Shutting-down-Threads-Cleanly.html
        Thread.currentThread().interrupt();
      }
    }
  }

thread.start();
© www.soinside.com 2019 - 2024. All rights reserved.