0

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 .

Shile
  • 33
  • 7

3 Answers3

3

I would recommend holding onto the Thread instance and then calling threadInstance.interrupt() right before the main(...) method exits.

Something like:

 public static void main(String[] args){
    MainClass mainClass = new MainClass();
    try {
        ...
        // do main stuff here
        ...
    } finally {
        mainClass.threadInstance.interrupt();
    }
 }

Then in your thread you'd do:

 while(!Thread.currentThread().isInterrupted()){
     ...
 }

You'd also want to handle InterruptedException correctly:

 try {
     Thread.sleep(1000);
 } catch (InterruptedException e) {
     // always a good pattern to re-interrupt the thread here
     Thread.currentThread().interrupt();
     // if we are interrupted quit
     return;
 }

Btw, it is very bad form to leak the instance of an object during construction to another thread:

 new MyThread(this);

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 use threadInstance.start() but not inside of the constructor like that.

Community
  • 1
  • 1
Gray
  • 115,027
  • 24
  • 293
  • 354
1

You can use CountDownLatch which is very convenient for such tasks as waiting other threads to finish some activity (you can change Thread.sleep(...) argument in main to, say, 12000L and see what happens):

import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

class OtherThread extends Thread {
    private final CountDownLatch sharedLatch;

    OtherThread(CountDownLatch sharedLatch) {
        this.sharedLatch = sharedLatch;
    }

    @Override
    public void run() {
        boolean wokenByMain = false;
        try {
            wokenByMain = sharedLatch.await(10000L, TimeUnit.MILLISECONDS);
        } catch (InterruptedException e) {
            e.printStackTrace();
            return; // or not return, whatever makes more sense in your case
        }
        System.out.println("heh: " + wokenByMain);
    }
}
class SOSample {

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch latch = new CountDownLatch(1);
        OtherThread otherThread = new OtherThread(latch);
        otherThread.start();
        System.out.println("Scheduled other thread to be started");
        Thread.sleep(1000L);
        System.out.println("going to release other thread");
        latch.countDown();
    }

}
Victor Sorokin
  • 11,878
  • 2
  • 35
  • 51
-1
public class MainClass extends JFrame implements Runnable {
  public static void main(String [] args) {
    final Thread t=new Thread(new MainClass() {
            public void run(){
              //something
            });
    Thread t2=new Thread(new MyThread() {
            public void run() {
              while(t.isAlive) {
                //something
              }
            }
    });
  }
}
durron597
  • 31,968
  • 17
  • 99
  • 158
  • 2
    I have formatted your code for you, but this answer would greatly benefit from some explanation as well. – durron597 Sep 15 '15 at 21:04
  • 1
    Consider improving your answer. _[Code-only answers may fall under 'Very Low Quality' ...and are candidates for deletion....We've always touted that we aren't a code factory. We are the people who teach others to fish. Code-only answers only feed a person for a day](http://meta.stackexchange.com/questions/148272/is-there-any-benefit-to-allowing-code-only-answers-while-blocking-code-only-ques)_ –  Sep 15 '15 at 23:53