I have a main class which spawns a thread, let’s call them MainClass and MyThread.
public class MainClass extends javax.swing.JFrame {
int sharedVariable;
MyThread threadInstance;
public MainClass (){
sharedVariable = 2;
threadInstance = new MyThread(this);
threadInstance.run();
}
public int getSharedVariable(){ return sharedVariable; }
public static void main(String[] args){
//begin main class
}
}
public class MyThread implements Runnable {
MainClass class;
public MyThread(MainClass main_class){
this.main_class= main_class;
}
@Override
public run(){
while(this.main_class is still active){
//grab status of sharedVariable and wait for x amount of time.
}
}
}
The problem is I do not know how to implement the while condition which checks if the MainClass instance is still alive and if it is, it has to use the this.main_class.getSharedVariable() to get the value of sharedVariable, then wait for x amount of time. MainClass has the main method .
I would recommend holding onto the
Threadinstance and then callingthreadInstance.interrupt()right before themain(...)method exits.Something like:
Then in your thread you’d do:
You’d also want to handle
InterruptedExceptioncorrectly:Btw, it is very bad form to leak the instance of an object during construction to another thread:
See here: Why shouldn't I use Thread.start() in the constructor of my class?
Also, you aren’t starting a thread when you call
threadInstance.run();. You are just running it in the current thread. You should usethreadInstance.start()but not inside of the constructor like that.