I need to create 5 threads and associate an ArrayList with each thread .I have another thread which will read values from a queue (one by one) and push that message to the
ArrayList associated with each thread which i created earlier . Then that thread should read value from the ArrayList and start executing. How can I do that?
I need to create 5 threads and associate an ArrayList with each thread .I
Share
You can use the Monitor class to synchronize your threads. Here is an example using five different locks and queues, one for each thread, based on your comments.
It’s important to protect with a lock any data shared between two different threads. Only the thread holding the lock should access the data.
The worker thread locks on its own personal object (in the syncs array), and, having the lock, then calls Monitor.Wait, which will release the lock.
The main thread may have already tried to lock that thread’s sync object, or soon will, it doesn’t matter because it won’t have access to that thread’s queue until it does have the lock. Then it is safe to queue up a message. The Monitor.Pulse call wakes up the waiting worker thread, but the worker stays stuck in its Monitor.Wait call until the main thread releases the lock (by falling out of the lock() { } code block.)
When Monitor.Wait returns to the worker, the lock will have been re-acquired.
You can’t always assume that the threads will pulse and wake at the same rate, which is why I have the extra while loop in the worker thread, to handle the case where the main thread has signaled a few times with several messages before the worker actually woke up to process them.
This example is much simplified — it doesn’t cover shutting the workers down, for example, but it should give you some ideas get started.