在Java中返回/停止在keypress上执行函数
我的程序中有一定的function,我想在按键时停止。 我为此设置了一个本机键盘钩子。 现在,当检测到该键时,我调用System.exit(0)。 但是,我不想退出程序,只是停止该操作并返回到它所调用的位置。 下面给出一个例子。
public class Main { public static void main(String[] args) { System.out.println("Calling function that can be stopped with CTRL+C"); foo(); // Should return when CTRL+C is pressed System.out.println("Function has returned"); } }
我已经尝试将调用foo()放在一个线程中,所以我可以调用Thread.interrupt()
但我希望函数调用是阻塞的,而不是非阻塞的。 在foo()
还有阻塞IO调用,所以我宁愿不处理中断,除非有必要,因为我必须处理ClosedByInterruptException
exception并且之前已经引起了问题。
foo()
的主体也很长,里面有很多函数调用,所以写if (stop == true) return;
在函数中不是一个选项。
有没有比制作阻塞线程更好的方法呢? 如果是这样,怎么样? 如果没有,我将如何制作阻止线程?
这个怎么样?
// Create and start the thread MyThread thread = new MyThread(); thread.start(); while (true) { // Do work // Pause the thread synchronized (thread) { thread.pleaseWait = true; } // Do work // Resume the thread synchronized (thread) { thread.pleaseWait = false; thread.notify(); } // Do work } class MyThread extends Thread { boolean pleaseWait = false; // This method is called when the thread runs public void run() { while (true) { // Do work // Check if should wait synchronized (this) { while (pleaseWait) { try { wait(); } catch (Exception e) { } } } // Do work } } }
(取自http://www.exampledepot.com/egs/java.lang/PauseThread.html而不是我自己的工作)
- Spring Error – java.lang.NoSuchMethodError:> org.springframework.beans.factory.annotation.InjectionMetadata。
- 当组件在paintComponent()之外加载图像时,JFrame显示为空白; 方法