关于Thread ThreadPool Parallel 的一些小测试demo
2024-09-03 03:35:20
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks; namespace TestProject
{
class Program
{
//异步:不阻塞主线程的一种编程方法
//多线程(new Thread): 多个线程去做一个事情 (注意共享变量的问题)(无法监测是否完成)
//线程池(new ThreadPool):省去线程重复创建回收的消耗。(无法检测执行任务是否完成)
//Task: Task在线程池的基础上进行了优化,并且可以检测到完成状态。
//Parallel:并行多个任务。(而且能监测完成状态)
//乐观锁悲观锁
static void Main(string[] args)
{
//int a = 0;
Stopwatch stopwatch = new Stopwatch(); #region 单线程
stopwatch.Start(); // 开始监视代码运行时间
for (int i = ; i < ; i++)
{
Console.WriteLine("thread:{0}", Thread.CurrentThread.ManagedThreadId);
Thread.Sleep();
}
// you code ....
stopwatch.Stop(); // 停止监视
ConsoleTime(stopwatch, "单线程");
#endregion #region ThreadPool(没办法检测是否完成哦!)这里监测到的时间是创建线程池所需要的时间
stopwatch.Start(); // 开始监视代码运行时间 ThreadPool.SetMaxThreads(, );
ThreadPool.SetMinThreads(, );
for (int i = ; i < ; i++)
{
ThreadPool.QueueUserWorkItem(new WaitCallback((obj) =>
{
Console.WriteLine("线程池输出: thread:{0}", Thread.CurrentThread.ManagedThreadId);
Thread.Sleep();
}), i.ToString());
}
// you code ....
stopwatch.Stop(); // 停止监视
ConsoleTime(stopwatch, "ThreadPool");
#endregion #region Thread(没办法检测完成!没有返回值没有办法检测状态。)这里监测到的时间仅仅只是创建这些线程所需要的时间。
stopwatch.Start(); // 开始监视代码运行时间
for (int i = ; i < ; i++)
{
Thread thread = new Thread(new ThreadStart(DoSomeThing));
thread.Start();
//Thread.Sleep(100);
}
// you code ....
stopwatch.Stop(); // 停止监视
ConsoleTime(stopwatch, "Thread");
#endregion #region Parallel
stopwatch.Start(); // 开始监视代码运行时间
var task = System.Threading.Tasks.Parallel.For(, , new ParallelOptions() { MaxDegreeOfParallelism = }, (i) =>
{
Console.WriteLine("{0},task:{1},thread:{2}", i, Task.CurrentId, Thread.CurrentThread.ManagedThreadId);
Task.Delay();
//提供的原子性操作,保证对a的值操作每一次都是原子性的
//System.Threading.Interlocked.Add(ref a, 1);
//a++;
});
stopwatch.Stop(); // 停止监视
ConsoleTime(stopwatch, "Parallel");
#endregion //Console.Write(a);
Console.ReadKey();
}
/// <summary>
/// 模拟做点什么同时输出当前线程id
/// </summary>
private static void DoSomeThing()
{
Console.WriteLine("DoSomeThing: thread:{0}", Thread.CurrentThread.ManagedThreadId);
Thread.Sleep();
}
/// <summary>
/// 模拟异步执行方法
/// </summary>
/// <returns></returns>
private static async Task DoSomeThing2()
{
await Task.Run(() =>
{
Console.WriteLine("DoSomeThing2: task:{0},thread:{1}", Task.CurrentId, Thread.CurrentThread.ManagedThreadId);
Thread.Sleep();
}
);
}
//输出当前代码段运行时间
private static void ConsoleTime(Stopwatch stopwatch, string BlockName)
{
TimeSpan timespan = stopwatch.Elapsed; //获取当前实例测量得出的总时间
Console.WriteLine("{0} ,代码执行时间:{1}(毫秒)", BlockName, timespan.TotalMilliseconds); //总毫秒数
stopwatch.Reset();
} }
}
最新文章
- Java 时间类-Calendar、Date、LocalDate/LocalTime
- HTML5小游戏之见缝插针
- [Android]关于Installation error: INSTALL_PARSE_FAILED_MANIFEST_MALFORMED ,修改包名
- .Net框架2.0和4.0版本对比
- IntelliJ_13书签
- 基于tomcat+spring+mysql搭建的个人博客
- AFnetworking3.1的基本使用
- Direct2D开发:纹理混合
- C++的三种继承方式简述
- 通过百度地图API将百度坐标转换成GPS经纬度
- Lisp与JAVA的酷毙结合——abcl
- R与数据分析旧笔记(十七) 主成分分析
- 【2017集美大学1412软工实践_助教博客】团队作业4——第一次项目冲刺(Alpha版本)小组 成绩
- python中openpyxl的用法【安装,以及一些基本的操作】
- Getting Started with Word2Vec
- 各大型网站架构分析收集-原网址http://blog.csdn.net/lovingprince/article/details/3379710
- echarts展示箱型图&;正态分布曲线
- AJAX请求时status返回状态明细表(转)
- YII创建应用
- 【CodeForces】679 A. Bear and Prime 100
热门文章
- Error from server (NotFound): the server could not find the requested resource (get services http:heapster:)
- git 版本撤销,回退等
- 【Python之路】特别篇--Python正则表达式
- 汇编call jmp理解
- 妙味课堂——JavaScript基础课程笔记
- mock的那点事
- DB 分库分表(2):全局主键生成策略
- git忽略提交:.gitignore
- State Threads之co-routine的创建和stack的管理
- 在Excel中,已知身份证号码,如何批量计算其实际年龄?