I am wondering if it is possible in java to have a class that implements Runnable and if an object of the class goes to wait() (so thread stops running until it receives a signal), can another object of the same class notify it to continue running ?
Ideally what i want to be able to do is:
public class ThreadClass implements Runnable{
public void run(){
//.. Does some arbitrary work
if( aCondition){ //have it wait until something signals it to contine exection.
this.wait();
}
//Continues to do more work.
//finished whatever it needed to do. Signal all other threads of this object type to continue their work.
this.notifyAll();
}
}
Is this possible and if so how would I go about doing it? I am trying to make it so that the object itself can manage itself and all other objects of the same type. So that no one using this class has to worry about managing it.
I am trying to make it so that the object itself can manage itself and all other objects of the same type. So that no one using this class has to worry about managing it.
If you want to make every instance know about every other instance, you'd need some sort of static collection... which then makes garbage collection tricky, as well as making it all hard to test.
I would suggest you have a separate manager type whose sole job is to manage instances of this class. Then you still only need to have the logic in one place, but you don't need to know about all instances of the type - the manager just needs to know what it's managing. You may even be able to create the API so that client code only needs to see the manager, and the individual instance are hidden.
EDIT: Just to clarify, you may not even need wait
/notifyAll
at all - prefer the higher-level constructs in java.util.concurrent
, which allow you to write producer/consumer scenarios without low-level operations such as wait
. This answer addresses the higher level question of letting objects know which other objects they should be communicating with. The question's idea of all objects of one type knowing about another will lead to problems, hence the suggestion of a manager class.
If( condition)
{ wait }
Ideally wait should be sorrounded by while condition instead of if block. Because client should make sure that the condition is satisfied before going ahead instead of soley relying on notify.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With