Java 异步等待 x 秒

Java asynchronously wait x seconds

详细说明我正在尝试做的事情:我正在 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,请原谅我的无知。

您可以通过像这样实现一个 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
      Thread.sleep(1000)
      System.out.println("Time to wake up");
    }
  }

thread.start();

使用Bukkit scheduler.

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

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