代码:
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Text; 5 using System.Threading.Tasks; 6 7 //引用相应命名空间 8 using System.Threading; 9 using System.Collections; 10 11 namespace ThreadDemo 12 { 13 class ThreadDemo 14 { 15 16 private Thread thread1; 17 18 private Thread thread2; 19 20 private ArrayList arraylist; 21 22 //删除所有数据之后,执行事件 23 private event EventHandler OnNumberClear; 24 25 /// <summary> 26 /// 构造函数 27 /// </summary> 28 /// <param name="Number">数字</param> 29 public ThreadDemo(int Number) 30 { 31 //创建随机对象 32 Random db = new Random(1000000); 33 34 //创建数组 35 arraylist = new ArrayList(Number); 36 37 //循环将产生的随机数放到数组中。 38 for (int i = 0; i < Number; i++) 39 { 40 arraylist.Add(db.Next().ToString()); 41 } 42 43 //ThreadStart表示在此线程上调用的方法 44 thread1 = new Thread(new ThreadStart(Run)); 45 46 //ThreadStart表示在此线程上调用的方法 47 thread2 = new Thread(new ThreadStart(Run)); 48 49 OnNumberClear += ThreadDemo_OnNumberClear; 50 } 51 52 /// <summary> 53 /// 事件执完成之后,执行事件 54 /// </summary> 55 /// <param name="sender"></param> 56 /// <param name="e"></param> 57 void ThreadDemo_OnNumberClear(object sender, EventArgs e) 58 { 59 Console.WriteLine("执行完成,停止所有线程!"); 60 thread1.Abort();//终止线程 61 thread2.Abort(); //终止线程 62 } 63 64 /// <summary> 65 /// 两个线程要执行的方法 66 /// </summary> 67 public void Run() 68 { 69 string stringValue = null; 70 while (true) 71 { 72 Monitor.Enter(this);//锁定,保持同步 73 stringValue = (string)arraylist[0]; 74 Console.WriteLine(Thread.CurrentThread.Name + "删除了" + stringValue); 75 arraylist.RemoveAt(0);//删除ArrayList中的元素 76 if (arraylist.Count == 0) 77 { 78 OnNumberClear(this, new EventArgs());//引发完成事件 79 } 80 Monitor.Exit(this);//取消锁定 81 Thread.Sleep(5); 82 } 83 } 84 85 /// <summary> 86 /// 启动两个线程 87 /// </summary> 88 public void Active() 89 { 90 91 thread1.Start(); 92 thread2.Start(); 93 } 94 95 96 /// <summary> 97 /// Main 98 /// </summary> 99 public static void Main() 100 { 101 ThreadDemo th = new ThreadDemo(200); 102 103 th.Active(); 104 } 105 } 106 }
时间: 2024-09-26 22:28:35