Arnav Sengupta Arnav Sengupta - 1 year ago 45
Java Question

Inter thread communication java

I want to make threads in my application talk with each other. My scenario is mentioned below: (searched for this, but didn't find anything)

For instance, 10 threads are doing something. Thread 1 encounters some condition on which it will safely terminate, but I also need it to tell all other threads to stop what they are doing and terminate safely.

One way to do this is to share a variable and each thread checks this variable before doing something. The caveat is that I need to keep checking this variable at certain checkpoints.

It would be better if there was some way for thread1 to just signal others to stop what they are doing and terminate safely.

Any such package available or something else which does this without complicating things too much?

Answer Source

There is little you can do that is clean (but check out my last point).

  1. Arrange to interrupt all other threads. Very untidy and will probably give you headaches
  2. Regularly check a variable (or queue). Probably a better approach but, as you say, is a little messy
  3. Refactor your code into smaller functions and use a threadpool to process them. If you detect that processing can be stopped, shut down the pool. Could be a lot of work but might be the most resilient solution
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download