发布:2019/10/16 23:13:54作者:管理员 来源:本站 浏览次数:1232
using System;1.调用执行
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Threading;
namespace ThreadTest
{
public class TestDemo : ThreadFactory<UserInfo>
{
private static int index = 0;
private IList<UserInfo> GetList()
{
IList<UserInfo> list = new List<UserInfo>();
for (var i = 0; i < 50; i++)
{
list.Add(new UserInfo
{
Id = ++index,
Name = "Name" + index
});
if (index == 500)
break;
}
return list;
}
public void Main()
{
index = 0;
var list = GetList();
Stopwatch sw = new Stopwatch();
sw.Start();
while (list != null && list.Count > 0)
{
Execute(list);
list = GetList();
}
sw.Stop();
Console.WriteLine($"单线程需要耗时{(index * 1000 / 1000)}秒");
Console.WriteLine($"执行完成 耗时{(sw.ElapsedMilliseconds / 1000)}秒");
}
protected override void Process(UserInfo info)
{
//处理这个方法至少1秒
Thread.Sleep(1000);
int threadId = Thread.CurrentThread.ManagedThreadId;
Console.WriteLine($"ThreadId={threadId} Id={info.Id} Name={info.Name}");
}
}
/// <summary>
/// 用户类
/// </summary>
public class UserInfo
{
public int Id { get; set; }
public string Name { get; set; }
}
}
2.实现方法
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
namespace ThreadTest
{
public abstract class ThreadFactory<T>
{
private AutoResetEvent wait_sync = new AutoResetEvent(false); // 用来控制:并发最大个数线程max_thread_number
private AutoResetEvent wait_main = new AutoResetEvent(false); // 用来控制:主程序的结束执行,当所有任务线程执行
private int min_thread_number = 1; //设置并行最小线程个数
private int max_thread_number = 5; //设置并行最大线程个数
private int total_thread_number = 0; //用来控制:主程序的结束执行,当所有任务线程执行完毕
private bool _isAlive = false;
/// <summary> 设置并行最小线程个数 </summary>
public int MinThreadNumber
{
get { return min_thread_number; }
set
{
min_thread_number = value;
//设置最小线程线程个数
ThreadPool.SetMinThreads(min_thread_number, min_thread_number);
}
}
/// <summary> 设置并行最大个线程个数 </summary>
public int MaxThreadNumber
{
get { return max_thread_number; }
set
{
max_thread_number = value;
//设置最大线程个数
ThreadPool.SetMaxThreads(max_thread_number, max_thread_number);
}
}
public void Execute(IList<T> list)
{
for (var i = 0; i < list.Count; i++)
{
if (total_thread_number >= max_thread_number)
wait_sync.WaitOne();
var j = i;
Task.Factory.StartNew(() =>
{
var info = list[j];
Process(info);
total_thread_number--;
if (total_thread_number < max_thread_number)
wait_sync.Set();// 任务线程,继续执行
if (j + 1 == list.Count)
wait_main.Set(); // 主程序线程,继续执行
});
total_thread_number++;
}
wait_main.WaitOne();
}
protected abstract void Process(T t);
}
}
3.线程工厂
© Copyright 2014 - 2024 柏港建站平台 ejk5.com. 渝ICP备16000791号-4