Code:
1 usingSystem;2 usingSystem.Collections.Generic;3 usingSystem.Linq;4 usingSystem.Text;5 usingSystem.Threading.Tasks;6 7 //referencing the corresponding namespace8 usingSystem.Threading;9 usingSystem.Collections;Ten One namespaceThreaddemo A { - classThreaddemo - { the - PrivateThread Thread1; - - PrivateThread thread2; + - PrivateArrayList ArrayList; + A //after all data is deleted, the event is executed at Private EventEventHandler onnumberclear; - - /// <summary> - ///constructor Function - /// </summary> - /// <param name= "number" >Digital</param> in PublicThreaddemo (intNumber ) - { to //creating random Objects +Random db =NewRandom (1000000); - the //Create an array *ArrayList =NewArrayList (number); $ Panax Notoginseng //The loop puts the resulting random number in the array. - for(inti =0; I < number; i++) the { + ArrayList. ADD (db. Next (). ToString ()); A } the + //ThreadStart represents the method that is called on this thread -Thread1 =NewThread (NewThreadStart (Run)); $ $ //ThreadStart represents the method that is called on this thread -Thread2 =NewThread (NewThreadStart (Run)); - theOnnumberclear + =threaddemo_onnumberclear; - }Wuyi the /// <summary> - ///after the event is completed, the execution event Wu /// </summary> - /// <param name= "Sender" ></param> About /// <param name= "E" ></param> $ voidThreaddemo_onnumberclear (Objectsender, EventArgs e) - { -Console.WriteLine ("execution complete, stop all threads! "); -Thread1. Abort ();//terminating a thread AThread2. Abort ();//terminating a thread + } the - /// <summary> $ ///two threads to execute a method the /// </summary> the Public voidRun () the { the stringStringValue =NULL; - while(true) in { theMonitor.Enter ( This);//lock, keep in sync theStringValue = (string) arraylist[0]; AboutConsole.WriteLine (Thread.CurrentThread.Name +"removed the"+stringvalue); theArrayList. RemoveAt (0);//Delete an element in a ArrayList the if(ArrayList. Count = =0) the { +Onnumberclear ( This,NewEventArgs ());//Raise Completion Event - } theMonitor.Exit ( This);//Cancel LockBayiThread.Sleep (5); the } the } - - /// <summary> the ///Start Two threads the /// </summary> the Public voidActive () the { - the Thread1. Start (); the thread2. Start (); the }94 the the /// <summary> the ///Main98 /// </summary> About Public Static voidMain () - {101Threaddemo th =NewThreaddemo ( $);102 103 th. Active ();104 } the }106}
C #-Threading operations