Question

I am using an actionListener to trigger an sequence of events and ultimatley this code is called:

public class ScriptManager {

public static Class currentScript;
private Object ScriptInstance;
public int State = 0;
// 0 = Not Running
// 1 = Running
// 2 = Paused

private Thread thread = new Thread() {
    public void run() {
        try {
            currentScript.getMethod("run").invoke(ScriptInstance);
        } catch(Exception e) {
            e.printStackTrace();
        }
    }
};

public void runScript() {
    try {
        ScriptInstance = currentScript.newInstance();
        new Thread(thread).start();
        State = 1;
        MainFrame.onPause();
    } catch (Exception e) {
        e.printStackTrace();
    }
}   

public void pauseScript() {
    try {
        thread.wait();
        System.out.println("paused");
        State = 2;
        MainFrame.onPause();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public void resumeScript() {
    try {
        thread.notify();
        System.out.println("resumed");
        State = 1;
        MainFrame.onResume();
    } catch (Exception e) {
        e.printStackTrace();
    }
}

public void stopScript() {
    try {
        thread.interrupt();
        thread.join();
        System.out.println("stopped");
        State = 0;
        MainFrame.onStop();
    } catch (Exception e) {
        e.printStackTrace();
    }
 }
}

The runnable is created and ran, however, the problem occurs when I try to use the any of the other methods, they lock my UI. (I'm assuming this is because im running this on the EDT) Does anyone know how to fix this?

Was it helpful?

Solution

That's not how you use wait and notify. They need to be executed on the thread that you are trying to pause and resume. Which means you need to send a message to the other thread somehow. There are various ways to do this, but the other thread needs to be listening for this message, or at least check for it occassionally.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top