2

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.

Tony Rad
  • 2,479
  • 20
  • 32
Aditya
  • 195
  • 3
  • 4
  • 12

1 Answers1

2

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();
ddmps
  • 4,350
  • 1
  • 19
  • 34
  • 1
    ok. so will it be right if I declare the lock and condition variables as final in one class and then pass an instance of that class to the second one. In that case, both the classes will have access to the same lock and condition variables right ? – Aditya Nov 19 '12 at 05:45
  • I would vote this up except that extending `Thread` is generally thought to be a bad idea due to the potential for programmer errors... better to implement `Runnable` – artbristol Nov 19 '12 at 10:41
  • @artbristol Why is there a bigger potential for programmer errors in extending `Thread`? The only real difference I see is that `Runnable` has to be implemented and `Thread` extended. To have shared resources in a `Runnable` you have to pass the same arguments which would make the two methods being practically the same. Unless you pass the same `Runnable` instance to several new Threads, which if anything is prone to programmer errors... – ddmps Nov 19 '12 at 11:17