java Semaphore north south que

ぐ巨炮叔叔 提交于 2019-12-04 22:04:16

You've only modeled the children, not the actual roundabout. I doubt each child needs its own thread, unless that's been mandated.

What seems a more useful approach is to make three threads, one for each queue, and one for the roundabout. The roundabout is the worker thread and the child queues are the producer threads. Your roundabout thread would have a circular buffer of children, each with a 'time to play' decided randomly when they enter the roundabout. The thread would periodically check the 'time to play' of each child and when any of them expire it would eject them randomly into the north or south queue and raise a semaphore that a space is open.

The two queue threads would each wait on the semaphore and whenever it went up, the first one to acquire it would put its child into the roundabout structure with a randomly chosen 'time to play'.

Alternatively you could have the roundabout thread eject people into the east and west playgrounds at random and have the queuing threads responsible for emptying them. You need to ensure that each shared collection (the circular buffer and the actual list of children in each of the queue threads) is properly handled in terms of synchronization. You will only need two classes, the roundabout thread and the queue thread, but there will be two instances of the queue thread, one for north and one for south.

Where are the semaphores? and where's the rest of the code? if this is all you have, it's not enough for me to help you, it'd feel like i'm doing the whole thing.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!