Search code examples
javamultithreadingsynchronizationlocksdata-sharing

Sharing Condition and Lock variable Across Classes in Java


I want to write a program where two separate threads run two objects and one thread waits to execute its code till it is signalled by the other.

Now to do this I want to use the Condition interface.

I am unable to figure out where to declare the lock and condition variables in my code such that both classes have access to it.

What I want to ask is, how do threads share the lock and condition variables so that it is ensured that they are signalling and waiting on the same condition.


Solution

  • The threads will have to have some sort of connection for this to work. If thread 1 has a reference to thread 2, the lock and condition variables may be in thread 2 and vice versa.

    If not, the variables will have to be in a separate class which both threads have access to. So, you'll have to pass the same instance of that class to both threads, so that instance becomes a shared resource. Following example assumes you have classes Thread1 and Thread2 that extends Thread with a constructor taking SharedResource as an argument:

    SharedResource sr = new SharedResource();
    Thread1 t1 = new Thread1(sr);
    Thread2 t2 = new Thread2(sr);
    t1.start();
    t2.start();