Answer the question
In order to leave comments, you need to log in
How to form a queue in a simple multi-threaded Java application?
Hello! I am learning Java and at the moment multithreading, the next task is a car wash with n number of boxes, workers and cars that arrive there, queue up and when a free box is freed, they take it for washing. Accordingly, we have the class car wash, car, box, worker. I suppose this is how the auto class forms a queue and starts workers (threads - demons) that execute some methods in the box and auto classes.
It is not clear yet how the process of building the queue itself takes place and whether the box is free or busy?
Thanks in advance!
ps It would be especially good to look at an example.
Use java.util.concurrent.*; assignment is not possible.
Answer the question
In order to leave comments, you need to log in
A semaphore would be good here.
Briefly about BlockingQueue-s, the rules are here
I would advise to make some implementation of Condition.
Roughly speaking, when locking, remember all the threads that have come to us, but it’s better to connect them in a queue, and when released, send a signal that we have free space and take the first one from this queue. In general, I advise you to look at the await and signal methods in the AbstractQueuedSynchronizer.
After your approximate implementation of the same mechanism, everything will be quite simple)
When you enter the queue, you check whether there is a place, if there is, then simply add it to the queue, if not, then we park the thread through an analogue of the await method, when exiting the method, the signal helmet, so that the first parked thread entered your queue.
Of course, you can try it easier, make a sychronized method for adding to the queue, and if we have a size no longer release it, make an infinite loop. And as soon as there is a place, then let go)
Decide for yourself how best.)
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question