在Java中返回/停止在keypress上执行函数 [英] Returning/Stopping the execution of a function on a keypress in Java
问题描述
我的程序中有一定的功能,我想在按键时停止。我为此设置了原生键盘钩。现在,当检测到该键时,我调用System.exit(0)。但是,我不想退出程序,只是停止该操作并返回到它被调用的位置。下面给出一个例子。
I have a certain function in my program that I want to stop on the press of a key. I have a native keyboard hook set up for that purpose. Right now, I call System.exit(0) when that key is detected. However, I don't want to exit the program, just stop that operation and return to where it was called. An example is given below.
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
异常并且之前已经出现过问题。
I've tried putting the call to foo() in a thread so I could call Thread.interrupt()
but I want the function call to be blocking, not non-blocking. Also there are blocking IO calls in foo()
so I'd rather not deal with interrupts unless it's necessary, because I'd have to deal with ClosedByInterruptException
exceptions and that has caused problems before.
还有 foo()的主体
非常长并且里面有很多函数调用,所以在函数中写入 if(stop == true)return;
不是一个选项。
Also the body of foo()
is very long and has many function calls inside it, so writing if (stop == true) return;
in the function is not an option.
有没有比制作阻塞线程更好的方法呢?如果是这样,怎么样?如果没有,我将如何制作阻止线程?
Is there a better way to do this than making a blocking thread? If so, how? If not, how would I make a blocking thread?
推荐答案
这个怎么样?
// 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 不是我自己的工作)
(taken from http://www.exampledepot.com/egs/java.lang/PauseThread.html not my own work)
这篇关于在Java中返回/停止在keypress上执行函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!