简体   繁体   中英

Java Thread.sleep(delay) not working

Hi I'm trying to execute task every X seconds and I have problem with it:

Thread joinThread = new Thread(() -> {
    for (int i = 0; i < amount; i++) {
        Player player = new Player(user, RandomUtils.randomString(10), host, p, event.getSession());
        player.join();
    }

    try {
        Thread.sleep(delay);
    } catch (InterruptedException ignored) {
        ignored.printStackTrace();
    }
});

joinThread.start();

It looks like Thread.sleep(delay) is ignored because my thread is executing itself every ms instead of delay

Here's my join method:

public void join(){
    GameProfile profile = session.getFlag("profile");
    Client c = new Client(host, port, new MinecraftProtocol(name), new TcpSessionFactory(proxy));
    c.getSession().addListener(new SessionAdapter() {
        @Override
        public void packetReceived(PacketReceivedEvent event) {
            if (event.getPacket() instanceof ServerJoinGamePacket) {
                user.setBotAmount(u.getBotAmount()+1);
                user.addBot(event.getSession());
                System.out.println("Player bot joined");
            }
        }

        @Override
        public void disconnected(final DisconnectedEvent event) {
            if(event.getCause() != null) event.getCause().printStackTrace();
            user.setBotAmount(u.getBotAmount() -1);
        }
    });
    c.getSession().connect();
}

If remove player.join(); , it's working like a charm.
Any advice? I don't see what I'm doing wrong.

First off, the body of a thread (the body of the run method) executes once.

You are trying to make a delay for each player. Then you need to put the Thread.sleep(delay) inside the loop after the player.join() :

for (int i = 0; i < amount; i++) {
    Player player = ...;
    player.join();

    try {
        Thread.sleep(delay);
    } catch (InterruptedException reallyIgnored) {}
}

Otherwise, you are going to make a delay after all the players are already processed which makes no sense.

Make sure that the delay variable is set correctly. The Thread.sleep takes time in milliseconds. To feel the difference, the value is supposed to be >1000 .

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