简体   繁体   中英

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?

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM