注意:如果電腦是單核單線程的,這么做是沒有意義的。
這里直接貼一下主要代碼
using System; using System.Collections.Generic; using System.Text; using System.Threading; using System.Data; namespace ThreadTest { class Moultithreading { //創建2個線程 Thread ThreadOne = new Thread(new ThreadStart(ThreadOne1)); Thread ThreadTwo = new Thread(new ThreadStart(ThreadTwo2)); //ListInfo用於存放待執行的任務,ListInfo2用於存放已經執行過的任務(做一個標記的作用) static List<string> ListInfo = new List<string>(); static List<string> ListInfo2 = new List<string>(); public Moultithreading() { //假定有20個待執行任務 for (int i = 0; i < 20; i++) { ListInfo.Add(i + ""); } ThreadOne.Start(); ThreadTwo.Start(); } /// <summary> /// 線程1執行邏輯 /// </summary> private static void ThreadOne1() { ThreadExecute("One"); } /// <summary> /// 線程2執行邏輯,與線程1相同 /// </summary> private static void ThreadTwo2() { ThreadExecute("Two"); } /// <summary> /// 線程執行任務的通用方法,這里因為2個線程執行邏輯相同,就寫到一起了。用一個參數加以區分 /// </summary> /// <param name="ThreadNum"></param> private static void ThreadExecute(string ThreadNum) { for (int i = 0; i < ListInfo.Count; i++) { try { //當前任務未執行過,且未被其他線程占用 if (!ListInfo2.Contains(ListInfo[i]) && Monitor.TryEnter(ListInfo[i], 1000)) { Console.WriteLine("線程" + ThreadNum + "執行了任務:" + ListInfo[i]);//執行任務 ListInfo2.Add(ListInfo[i]);//任務執行完添加標記 Thread.Sleep(400); } } finally { if (Monitor.TryEnter(ListInfo[i])) { Monitor.Exit(ListInfo[i]);//釋放鎖 } } } } } }
執行結果:

