目的:
多个按钮点击新建线程执行某个任务。实现多线程执行任务,总数不超过某个数值,超过则等待执行完成才可以再次点击。
编程思路:
使用原子锁计算当前线程总数、线程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);
}
...
}