Self Techy
Self Techy

Reputation: 40

How to share a variable between two sub classes that implements runnable

I have a main class and two subclasses, subClass1 and subClass2 that implements runnable...

I have run the two threads simultaneously

by calling

t1.start // t1 for subclass1

t2.start // t2 for subclass2

Now, I want t1 to run till the t2 completes.

I can add a boolean flag within the method in subclass2 to recognize that the execution has been completed; Now I need to pass that information(boolean variable) to subclass1 to stop the execution of a set of codes from within it. [have used while(true) loop;]

so how can i create a common variable that can be accessed by both sub classes?

Can anybody please suggest me a solution for this?

Upvotes: 1

Views: 348

Answers (2)

Kayaman
Kayaman

Reputation: 73558

Pass an AtomicBoolean to the subclasses.

public class SubClass1 implements Runnable {
    private AtomicBoolean b;
    public SubClass1(AtomicBoolean b) {
        this.b = b;
    }

    public void run() {
        while(b.get()) {  // Assuming SubClass2 sets it to false when it's no longer running
            // Do something
        }
    }
}

Implementing SubClass2 is left as an exercise to the OP.

Upvotes: 3

Mateusz Kubuszok
Mateusz Kubuszok

Reputation: 27535

If possible I'd recommend to avoid sharing mutable state in concurrent environment, but assuming you have one of those cases where it cannot be avoided you can try something like (adjust for your own needs):

class SharedState {
  public final Object mutex = new Object();
  public boolean variable;
}

class Subclass extends MyClass1 implements Runnable {
  private SharedState sharedState;

  public Subclass1(SharedState sharedState) {
    this.sharedState = sharedState;
  }

  // ...

  @Override
  public void run() {
    // ...
    synchronized(sharedState.mutex) {
      // access sharedState.variable
    }
    // ...
  }
}

Basically create SharedState outside and inject into your subclasses on creation (or create it within one of them, retrieve and inject into another, whatever). Then use that shared variable remembering all you know about trickiness of shared state.

Upvotes: 1

Related Questions