您好我每隔X
秒尝试执行一次任务,我遇到问题:
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();
看起来Thread.sleep(delay)
被忽略了,因为我的线程每隔ms执行一次而不是延迟
这是我的join
方法:
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();
}
如果删除player.join();
,它就像魅力一样
有什么建议?我不知道自己做错了什么。
答案 0 :(得分:1)
首先,线程的主体(run
方法的主体)执行一次。
你正试图为每个玩家做出延迟。然后,您需要将Thread.sleep(delay)
放在player.join()
:
for (int i = 0; i < amount; i++) {
Player player = ...;
player.join();
try {
Thread.sleep(delay);
} catch (InterruptedException reallyIgnored) {}
}
否则,在所有玩家都已经处理完毕后你将会延迟这是没有意义的。
确保delay
变量设置正确。 Thread.sleep
需要时间(以毫秒为单位)。为了感受差异,该值应为>1000
。