Returning/Stopping the execution of a function on

2019-06-04 02:09发布

问题:

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)