c# 多線程等待同步

目的:

多個按鈕點擊新建線程執行某個任務。實現多線程執行任務,總數不超過某個數值,超過則等待執行完成纔可以再次點擊。

編程思路:

使用原子鎖計算當前線程總數、線程Join 等待執行完畢。

public class test

{

      ...

      private int threadCount = 0;  //當前線程總數

      private int maxThreadCount = 5; //一次最多5個工作線程

      List<Thread> threads = new List<Thread>(); //保存所有的工作線程



      public ThreadFunc_1(Object param)

      {

              ...

              Interlocked.Decrement(ref threadCount);

              return;

      }

      

     public ThreadFunc_2(Object param)

      {

              ...

              Interlocked.Decrement(ref threadCount);

              return;

      }

      private void Button1_Click(object sender, EventArgs e)

      {

              if (threadCount > maxThreadCount)

              {

                         foreach (Thread thread in threads)

                         {

                                    thread.Join(); //等待

                         }

                         threads.Clear();

                         return;

              }

              //線程沒有超過上線,則新建線程

              Thread t = new Thread(new ParameterizedThreadStart(ThreadFunc_1));

              t.isBackgroud = true;

              t.Start(param);

              threads.Add(t); //保存到線程池

              Interlocked.Increment(ref threadCount);

      }



     private void Button2_Click(object sender, EventArgs e)

      {

              if (threadCount > maxThreadCount)

              {

                         foreach (Thread thread in threads)

                         {

                                    thread.Join(); //等待

                         }

                         threads.Clear();

                         return;

              }

              //線程沒有超過上線,則新建線程

              Thread t = new Thread(new ParameterizedThreadStart(ThreadFunc_2));

              t.isBackgroud = true;

              t.Start(param2);

              threads.Add(t); //保存到線程池

              Interlocked.Increment(ref threadCount);

      }

      ...
}

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章