Using System;
Using System. Collections;
Using System. Collections. Generic;
Using System. Threading;
/// <Summary>
/// Example of a thread is often encountered during development. If a background operation is time-consuming, we can start a thread to execute the time-consuming operation, and the program continues to execute it. In some cases, synchronization and collaboration among multiple threads may occur. The following example shows how to work collaboratively between two threads.
///
/// The idea of this program is to do one thing together (delete elements from an ArrayList). If the execution is complete, both threads stop.
/// By Zhou Gong
/// Time:
// Original address: http://blog.csdn.net/zhoufoxcn
/// </Summary>
Public class ThreadDemo
{
Private Thread threadOne;
Private Thread threadTwo;
Private ArrayList stringList;
Private event EventHandler OnNumberClear; // event triggered by data deletion completion
Public static void Main ()
{
ThreadDemo demo = new ThreadDemo (1000 );
Demo. Action ();
}
Public ThreadDemo (int number)
{
Random random = new Random (1000000 );
StringList = new ArrayList (number );
For (int I = 0; I <number; I ++)
{
StringList. Add (random. Next (). ToString ());
}
ThreadOne = new Thread (new ThreadStart (Run); // two threads work together to do one thing
ThreadTwo = new Thread (new ThreadStart (Run); // The two threads work together to do one thing.
ThreadOne. Name = "thread 1 ";
ThreadTwo. Name = "thread 2 ";
OnNumberClear + = new EventHandler (ThreadDemo_OnNumberClear );
}
/// <Summary>
/// Start work
/// </Summary>
Public void Action ()
{
ThreadOne. Start ();
ThreadTwo. Start ();
}
/// <Summary>
/// Work done together
/// </Summary>
Private void Run ()
{
String stringValue = null;
While (true)
{
Monitor. Enter (this); // locked to maintain synchronization
StringValue = (string) stringList [0];
Console. WriteLine (Thread. CurrentThread. Name + "deleted" + stringValue );
StringList. RemoveAt (0); // Delete the element in ArrayList
If (stringList. Count = 0)
{
OnNumberClear (this, new EventArgs (); // triggers a completion event
}
Monitor. Exit (this); // unlock
Thread. Sleep (5 );
}
}
// After the execution is complete, stop all threads
Void ThreadDemo_OnNumberClear (object sender, EventArgs e)
{
Console. WriteLine ("the execution is finished and all threads are stopped. ");
ThreadTwo. Abort ();
ThreadOne. Abort ();
}
}
Note: More than this method is required for thread synchronization. The event is used here and the thread is terminated in the event handler (this method is used mainly to answer a friend's question from the csdn Forum ).
Experience New Blog previous article: C # messy HtmlAgilityPack next article: I won 4 after breaking up