Thread.sleep()阻止当前线程(按住键的线程)执行。
如果希望它在给定的时间内按住键,也许应该在并行线程中运行它。
这是一个解决Thread.sleep()问题的建议(使用命令模式,以便您可以创建其他命令并随意交换它们):
public class Main {public static void main(String[] args) throws InterruptedException { final RobotCommand pressAKeyCommand = new PressAKeyCommand(); Thread t = new Thread(new Runnable() { public void run() { pressAKeyCommand.execute(); } }); t.start(); Thread.sleep(5000); pressAKeyCommand.stop(); }}class PressAKeyCommand implements RobotCommand {private volatile boolean isContinue = true;public void execute() { try { Robot robot = new Robot(); while (isContinue) { robot.keyPress(KeyEvent.VK_A); } robot.keyRelease(KeyEvent.VK_A); } catch (AWTException ex) { // Do something with Exception }} public void stop() { isContinue = false; }}interface RobotCommand { void execute(); void stop();}


