D
D
DR_Demons2014-12-02 00:48:16
Java
DR_Demons, 2014-12-02 00:48:16

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

2 answer(s)
Y
YV, 2014-12-02
@targetjump

A semaphore would be good here.
Briefly about BlockingQueue-s, the rules are here

N
Nikolai Pavlov, 2014-12-02
@gurinderu

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 question

Ask a Question

731 491 924 answers to any question