Returning/Stopping the execution of a function on a keypress in Java

淺唱寂寞╮ 提交于 2019-12-08 07:50:47

问题


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");
    }
}

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.

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?


回答1:


How about this?

// 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
        }
    }
}

(taken from http://www.exampledepot.com/egs/java.lang/PauseThread.html not my own work)



来源:https://stackoverflow.com/questions/10522663/returning-stopping-the-execution-of-a-function-on-a-keypress-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!