Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I use wait/notifyAll

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.

like image 422
user597608 Avatar asked Oct 21 '12 06:10

user597608


2 Answers

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.

like image 68
Jon Skeet Avatar answered Oct 02 '22 01:10

Jon Skeet


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.

like image 36
Htaras Avatar answered Oct 02 '22 02:10

Htaras