To ensure the thread security of the queue, all operations must be performed through this package.
Enumeration through a set is essentially not a thread-safe process. Other threads can modify the set even when synchronizing the set, which causes an exception in the number of enumerations. To ensure thread security during enumeration, you can lock the set during the enumeration process or catch exceptions caused by changes made by other threads.
The following example shows how to synchronize the queue, how to determine whether the queue is synchronized, and how to use the synchronized queue.
[C #]
Using system;
Using system. collections;
Public class samplesqueue {
Public static void main (){
// Creates and initializes a new queue.
Queue myq = new Queue ();
Myq. enqueue ("");
Myq. enqueue ("quick ");
Myq. enqueue ("brown ");
Myq. enqueue ("Fox ");
// Creates a synchronized wrapper around the queue.
Queue mysyncdq = queue. synchronized (myq );
// Displays the sychronization status of both queues.
Console. writeline ("myq is {0}.", myq. issynchronized? "Synchronized": "not synchronized ");
Console. writeline ("mysyncdq is {0}.", mysyncdq. issynchronized? "Synchronized": "not synchronized ");
}
}
/*
This code produces the following output.
Myq is not synchronized.
Mysyncdq is synchronized.
*/
By comparing the running results, we can see that the queue packaged by the queue. Synchronized Method is synchronized, and those without packaging are not synchronized. It can be declared at the instantiation,
// Creates a synchronized wrapper around the queue.
Queue mysyncdq = queue. synchronized (New Queue ());
In this way, the synchronization object lock of the queue can be used in a multi-threaded environment to prevent multiple threads from simultaneously writing the queue. To prevent other threads from accessing the queue object, you can use lock (Queue.