According to Oracle's documentation for Thread.sleep:
Thread.sleep causes the current thread to suspend execution for a specified period.
I am wondering what is considered the current thread.
I have a simple interface called Function:
public interface Function {
public abstract void run(TomVM vm);
}
And a class that contains instances of Function as well as a nested SwingWorker and Function class:
public class MyApp{
//Function that will be called by a SwingWorker
Function myFunction;
//Worker thread that will call the run() member of Functions
MyWorker myWorker;
public void start(){
//Initialize functions
myFunction = new WrapSleep(); //Object that calls sleep
//Start worker thread
myWorker = new MyWorker();
myWorker.execute();
}
private class MyWorker extends SwingWorker<Object, Object>{
@Override
protected Object doInBackground() throws Exception {
//There would normally be a loop here to call
//run for a list of Functions
//Have an arbitrary Function object run
myFunction.run(); //In this case WrapSleep.run()
}
}
//Sleep for a period of time
public final class WrapSleep implements Function {
public void run() {
try {
Thread.sleep(5000)
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
//Display a message
public final class WrapPrint implements Function{
@Override
public void run() {
JOptionPane.showMessageDialog(null, "Hello World");
}
}
}
In the actual application, MyApp, would display a window and execute the SwingWorker which drives a virtual machine that interprets compiled code of a basic language. There would be a much longer list of functions, as well as a list of instructions that tells the virtual machine which functions to call. Depending on the user's input, WrapSleep.run() may be followed by any number of WrapPrint.run() calls. As far as I'm aware the VM functions as it should in regards to properly interpreting the user's code.
The issue I'm having is that when WrapSleep.run() is called, the app behaves as though the VM has completed successfully without displaying messages that would normally be displayed by WrapPrint.run() or without pausing extend periods of time.
Since the instance of WrapSleep is not a member of MyWorker and it was not initialized by the thread, does calling WrapSleep.run() within MyWorker only function as a callback and only cause the thread WrapSleep was initialized in to sleep? - allowing MyWorker.doInBackground() to complete without pausing
I would prefer that the SwingWorker does not have Function members, but at what scope would I need to define the list of Functions so that Thread.sleep() causes the SwingWorker to sleep properly? Or is my assumption incorrect that the thread where the function is initialized is sleeping?