1

I need to use multiple threads, some of them are running, some of them are waiting until some other threads would wake them up. Lets say I have thread A, B, C, D and want to be able to wake/sleep any thread from any other. So, for instance, I want A to have a possibility to wake/sleep B, C, D; I want B to have a possibility to wake/sleep A, C, D etc For this purpose I decided to go for BlockingQueue so that I add kind of messages to BlockingQueue i.e.

blockingQueue.put("Start A"); or blockingQueue.put("Stop A"); 

And this queue is shared among all the threads so that every thread waits until message for it appears. However, this approach, apparently, has a big disadvantage: when some thread is listening for message which is intended for this thread (thread A waits for message "Start A" and must ignore all other messages like "Start B" etc), it must explicitly check if message for him is in the queue so I must use .contains() method and write some code in order to implement what I need. However, perhaps, there is some kind of blocking set for this purpose. The set which would allows to do the following:

blockingSet.get(E) //wait until element E appears in the set
Andrey Yaskulsky
  • 2,458
  • 9
  • 39
  • 81
  • There is something strange in your question and the use of BlockingQueue. Could you please give us the bigger picture? Why do you want A to sleep B? – Tobias Otto Oct 20 '16 at 13:41
  • You may want a `Map` or something similar, where each thread waits on its own `CyclicBarrier`, and each thread that wants to talk to it, looks up the correct barrier in the map. But this is easy for wake - what did you have in mind for sleep? The threads themselves will have to check if anybody told them to sleep, you can't force a thread to suspend itself. – RealSkeptic Oct 20 '16 at 13:49
  • @TobiasOtto I'm trying to create something like small framework for internal usage. So the main idea is that we will have many threads and want to have a single channel of communication between them so that any thready may contact any other – Andrey Yaskulsky Oct 20 '16 at 13:49
  • Something like this? https://en.wikipedia.org/wiki/Publish%E2%80%93subscribe_pattern. Please look at: https://stackoverflow.com/questions/3987391/why-people-use-message-event-buses-in-their-code – Tobias Otto Oct 20 '16 at 13:52
  • @TobiasOtto yes, exactly, but between threads, not between JMS brokers – Andrey Yaskulsky Oct 20 '16 at 13:53
  • Still not clear what exactly do you want to do. Do you want to pass various messages/commands, or is it really just starting and stopping a particular thread? – Stanislav Lukyanov Oct 26 '16 at 22:59

0 Answers0