1

我的 Java 程序中有一个函数等待用户按下空格键。我想对此进行修改,以便在经过一定时间并且仍未按下空间的情况下该函数也将返回。

我想保持这个功能不变并且不改变样式,所以我非常感谢修改这个功能的答案。谢谢!

public void waitForSpace() {
        final CountDownLatch latch = new CountDownLatch(1);
        KeyEventDispatcher dispatcher = new KeyEventDispatcher() {
            public boolean dispatchKeyEvent(KeyEvent e) {
                if (e.getID() == KeyEvent.KEY_PRESSED && e.getKeyCode() == KeyEvent.VK_SPACE) {
                    latch.countDown();
                }
                return false;
            }
        };
        KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(dispatcher);
        try {
            //current thread waits here until countDown() is called (see a few lines above)
            latch.await();
        } catch (InterruptedException e1) {
            e1.printStackTrace();
        }  
        KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventDispatcher(dispatcher);
    }
4

2 回答 2

2

尝试CountDownLatch#await(long, TimeUnit)改用...

public void waitForSpace() {
    final CountDownLatch latch = new CountDownLatch(1);
    KeyEventDispatcher dispatcher = new KeyEventDispatcher() {
        public boolean dispatchKeyEvent(KeyEvent e) {
            if (e.getID() == KeyEvent.KEY_PRESSED && e.getKeyCode() == KeyEvent.VK_SPACE) {
                latch.countDown();
            }
            return false;
        }
    };
    KeyboardFocusManager.getCurrentKeyboardFocusManager().addKeyEventDispatcher(dispatcher);
    try {
        //current thread waits here until countDown() is called (see a few lines above)
        latch.await(30, TimeUnit.SECONDS);
    } catch (InterruptedException e1) {
        e1.printStackTrace();
    }  
    KeyboardFocusManager.getCurrentKeyboardFocusManager().removeKeyEventDispatcher(dispatcher);
}
于 2013-06-06T02:53:31.103 回答
1

我相信您需要使用 ExecturerService 和 Future 来实现这一点。您可以设置未来完成的执行时间。您需要将代码包装在 Thread 类的 run 方法中等待用户输入。一旦你这样做并假设你称你为任务,那么你可以这样做:

public class Test {
    public static void main(String[] args) throws Exception {
        ExecutorService executor = Executors.newSingleThreadExecutor();
        Future<String> future = executor.submit(new Task());

        try {
            System.out.println("Started..");
            System.out.println(future.get(5, TimeUnit.SECONDS));
            System.out.println("Finished!");
        } catch (TimeoutException e) {
            System.out.println("Terminated!");
        }

        executor.shutdownNow();
    }
}

根据您的需要修改代码。

于 2013-06-06T01:05:06.443 回答