简体   繁体   中英

How to monitor a thread's state in Java?

Provided that there are 2 threads: A and B . I want:

  1. If A switches to sleep, then B switches to sleep too.

  2. If A is awake, then B is awake too.

Is there a way to implement that?

If you need to synchronize those Threads, you can use CyclicBarier.

It is a barier on which threads await. It works that threads are awaiting on it and if the number of awaiting threads reach the number specified then it wakes all threads and they continue to work. So it is a way to synchronize a bunch of threads to do one step and wait till each other finishes this step before doing next step.

Not directly. Sleep and wake are not lifecycle events on threads that user code has an opportunity to respond to. There is no way to call Thread.sleep() or Thread.wake() on another thread, as the remaining non-deprecated Thread operations only work on the current thread.

Represent the relationship between the work done by threads A and B more explicitly, for instance with queues. Thread A consumes work from a queue then puts the results on a queue consumed by Thread B . When there is work, both threads are working, when there is no work, both threads are sleeping.

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