简体   繁体   中英

Multithreading problems

I'm trying get more into multithreading in Java, but my endeavors have been stopped at this code:

package io.nlaz.test.commands;

import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.TabExecutor;
import org.bukkit.entity.Player;

import java.util.List;

public class test implements TabExecutor {
        @Override
    public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
        try {
            Thread a24 = new Thread(() -> {
                try {
                    Thread.sleep(1000);
                    sender.sendMessage("2");
                    Thread.sleep(2000);
                    sender.sendMessage("4");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            Thread a35 = new Thread(() -> {
                try {
                    Thread.sleep(3000);
                    sender.sendMessage("3");
                    Thread.sleep(2000);
                    sender.sendMessage("5");
                } catch (Exception e) {
                    e.printStackTrace();
                }
            });

            sender.sendMessage("1");
            a24.start();
            a35.start();
        } catch (Exception e) { e.printStackTrace(); }
        return false;
    }

    @Override
    public List<String> onTabComplete(CommandSender sender, Command command, String alias, String[] args) {
        return null;
    }
}

When the code is run, it supposed to send a message counting up to 5 every second. but when run it get's up to 2, then waits for the a24 thread to finish, then executes a35. I've looked up possible solutions to this, however they all either lead to the main thread getting paused, or the exact same problem as I already have.

I do have a part of it might be because I'm using Thread.sleep() and not something like Thread.currentThread().wait() . However when I use that method, I get an error saying java.lang.IllegalMonitorStateException: current thread is not owner . Any suggestions help, thank you!

Do NOT use Thread with Bukkit's plugins. Spigot has his own threading system.

BukkitTask task = Bukkit.getScheduler().runTaskTimer(myPlugin, new Runnable() {
   private int timer = 4;

   @Override
   public void run() {
      if(timer == 4 || timer ==2) {
          sender.sendMessage("Time: " + timer);
      }
      if(timer == 0) {
          task.cancel();
      }
      timer--;
   }
});

Documentation

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM