Home > Back-end >  Can't brain, ask everybody the teacher (thread)
Can't brain, ask everybody the teacher (thread)

Time:10-04

I want to do a multithreaded code generator factory consumer
Want to realize the function of the two producers consumers two factory 1
Factory production in consumer spending and bread production amount to 20 producers to stop production wait sleep, consumers in bread production and consumption goods inventory to wake producers began to produce zero

The difficulty is the factory now is thread lock, goods less than 20 when two threads of producers in competition at the same time the lock to the production of bread, consumer is in competition locking to consumption of bread at the same time, so the question comes, only one lock, if consumers take it to the producers will not lock the two producers will not lock the competition to produce bread, if the lock is producers take go to, the same two consumer will not lock competition to consumption of bread, I want to achieve is a lock of his own between producers and consumers between has a lock of his own, when producers can wait consumers through notify awaken producers, I am a self-taught, so there is no teacher can only to BBS hard everyone, this function can be achieved

CodePudding user response:

I think you can adjust a little bit about the design
You can let produce objects on a regular basis "outbound"
That is to say, has just been produced bread in a collection
Consumers can not directly access the collection
In the set of system on a regular basis will this bread "outbound" transfer to another for the use of consumer after the collection of
Consumers can access this consumption with bread collection
So it will be only in the regular bottleneck, outbound transfer and generate competitive when the
But as long as the "transfer" short enough, the impact on the production should be fairly small

CodePudding user response:

Write a monitoring thread, hand inside, the producers of consumers lock monitoring thread while there are two synchronized blocks, the first block of code for producers to lock, whether the product into the 20th, if to continue to get consumers lock, the number of product producers will reset to zero, consumer product number assignment for 20, consumers lock. NotifyAll (),

CodePudding user response:

The second synchronized block on the contrary,