43_2013年11月22日 线程池 Socket(Thread Lock Process 摇奖 线程池ThreadPool)
1》模拟线程池,生产者消费者问题
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace Product { class Program { static void Main(string[] args) { //创建一个池子 MyConncetion[] connectionArry =new MyConncetion[100]; //索引 int index = -1; //创建10个消费者 for (int i = 0; i < 100; i++) { //其中的一个消费者 Thread thread = new Thread(() => { while (true) { lock (connectionArry) { if (index >= 0) { connectionArry[index] = null; Console.WriteLine("消费一个产品:" + index); index--; } } Thread.Sleep(200); } }); thread.IsBackground = true; thread.Start(); } //创建5个生产者 for (int i = 0; i < 5; i++) { //其中的一个消费者 Thread thread = new Thread(() => { while (true) { //lock后面要跟一个引用类型的实例。 锁住同一个对象(引用地址)就互斥 lock (connectionArry)//lock(this) { if (index < 99) { connectionArry[index + 1] = new MyConncetion(); Console.WriteLine("生产一个产品:" + (index+1)); index++; } } Thread.Sleep(500); } }); thread.IsBackground = true; thread.Start(); } Console.ReadKey(); } } public class MyConncetion { } }
2.》摇奖代码
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; using System.Windows.Forms; namespace YaoJiangFrm { public partial class MainFrm : Form { private List<Label> lbLisnt = new List<Label>(); private Thread threadStart; private bool isRuning = false; public MainFrm() { InitializeComponent(); //Control.CheckForIllegalCrossThreadCalls = false; } private void MainFrm_Load(object sender, EventArgs e) { for (int i = 0; i < 6; i++) { Label lb = new Label(); lb.Text = "0"; lb.AutoSize = true; lb.Location = new Point(50 * i + 50, 100); this.Controls.Add(lb); lbLisnt.Add(lb); } } private void btnStart_Click(object sender, EventArgs e) { isRuning = true; Thread thread = new Thread(() => { Random r = new Random(); //不停改变lb的值 while (isRuning) { foreach (var item in lbLisnt) { string str = r.Next(0, 10).ToString(); if (item.InvokeRequired) { item.Invoke(new Action<string>(s => { item.Text = s; }),str); } else { item.Text = str; } } Thread.Sleep(200); } }); thread.IsBackground = true; thread.Start(); threadStart = thread; } private void btnStop_Click(object sender, EventArgs e) { isRuning = false; //if(threadStart==null|| (!threadStart.IsAlive)) //{ // return; //} //threadStart.Abort(); } void timer1_Tick(object sender, EventArgs e) { Console.WriteLine("11"); } } }
3》Process
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Diagnostics; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace WinFrmProcess { public partial class MainFrm : Form { public MainFrm() { InitializeComponent(); } private void btnOutputAllProcessInfos_Click(object sender, EventArgs e) { var allProcess = Process.GetProcesses(); foreach (var item in allProcess) { //Console.WriteLine(item.ProcessName+" " + item.Id); //item.Kill(); } } private void btnOpenNotepad_Click(object sender, EventArgs e) { //Process.Start("notepad","kkk.txt"); //Process.Start("iexplore.exe", "www.itcast.cn"); //Process.Start(@"C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Binn\fdlauncher.exe", "-s MSSQL10_50.MSSQLSERVER"); Process.Start(@"G:\NetClass\黑马9期\2013年11月22日 线程池 Socket\代码\WinFrmProcess\MainParamters\bin\Debug\MainParamters.exe", "ssss 2 4 33"); } } }
4》线程池ThreadPool
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace WaitCallBackQueue { class Program { static void Main(string[] args) { //线程队列 Queue<WaitCallback> queue =new Queue<WaitCallback>(); //入队 queue.Enqueue(a => { Console.WriteLine("ssss"); }); //调用线程池的线程执行 ThreadPool.QueueUserWorkItem(a => { Console.WriteLine("ssss"); }); } } }
5》带参数的线程
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace ThreadStartParamterDemo { class Program { static void Main(string[] args) { //ParameterizedThreadStart Thread thread =new Thread((s) => { Console.WriteLine( s); }); thread.Start("sssssss"); Console.ReadKey(); } } }
6》线程池基础
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Text; using System.Threading; namespace ThreadPoolDemo { class Program { static void Main(string[] args) { //WaitCallback //线程池的线程本身都是 后台线程。 //线程池的线程优势:线程可以进行重用。 //线程池 vs 手动创建线程 //启动一个线程:开辟一个内存空间,1M内存,线程有可能占用部分的寄存器 //线程非常多的时候,操作系统的花费大量时间用在线程切换。 // //ThreadPool.QueueUserWorkItem(s => //{ // Console.WriteLine(s); //},"shit"); //Stopwatch sw =new Stopwatch(); //sw.Start(); //for (var i = 0; i < 100; i++) //{ // new Thread(() => // { // int i1 = 0; // //Console.WriteLine( ++i1); // i1++; // }).Start(); //} //sw.Stop(); //Console.WriteLine(sw.Elapsed.TotalSeconds); //sw.Restart(); //for (var i = 0; i < 100; i++) //{ // ThreadPool.QueueUserWorkItem((s) => // { // int i1 = 0; // //Console.WriteLine(++i1); // Console.WriteLine(Thread.CurrentThread.ManagedThreadId); // i1++; // }); //} //sw.Stop(); //Console.WriteLine(sw.Elapsed.TotalSeconds); //获取线程池最大的线程数据 int numMax = 0; int runNumMax = 0; ThreadPool.GetMaxThreads(out numMax,out runNumMax); Console.WriteLine(numMax+ " " + runNumMax); //ThreadPool.GetMinThreads(); Console.ReadKey(); } } }
7》异步调用委托
using System; using System.Collections.Generic; using System.Linq; using System.Runtime.Remoting.Messaging; using System.Text; using System.Threading; using System.Threading.Tasks; namespace AsynDel { class Program { static void Main(string[] args) { Console.WriteLine(" Main Thread:"+Thread.CurrentThread.ManagedThreadId); Func<int, int, string> delFunc = (a, b) => { Console.WriteLine(" Delegate Thread:" + Thread.CurrentThread.ManagedThreadId); Thread.Sleep(20000); return (a + b).ToString(); }; //string str = delFunc(3, 4); //异步调用委托 //delFunc.BeginInvoke(3, 4, null, null); //内部原理就是:使用了一个线程池的线程去执行了委托指向的方法。 #region 异步委托 简单方式 ////拿到异步委托的结果 //IAsyncResult result = delFunc.BeginInvoke(3, 4, null, null); ////if (result.IsCompleted) ////{ ////} ////EndoInvoke方法会阻塞当前的线程,直到异步委托指向完成之后,才能继续往下执行。 //string str = delFunc.EndInvoke(result); //Console.WriteLine(str); #endregion #region 有回调函数的异步委托 //delFunc.BeginInvoke(5, 6, MyAsyncCallback, "123"); delFunc.BeginInvoke(5, 6, MyAsyncCallback, delFunc); #endregion Console.ReadKey(); } //回调函数:是异步委托方法执行完成之后,再来调 回调函数。 public static void MyAsyncCallback(IAsyncResult ar) { var del = (Func<int, int, string>)ar.AsyncState; string str = del.EndInvoke(ar); ////1、拿到异步委托执行的结果 //AsyncResult result = (AsyncResult)ar; //var del = (Func<int, int, string>)result.AsyncDelegate; //string returnValue = del.EndInvoke(result); //Console.WriteLine("返回值是:"+returnValue); ////2、拿到给回调函数的参数。 //Console.WriteLine("传给异步回调函数的参数:"+result.AsyncState); Console.WriteLine("回调函数的线程 的id是:"+Thread.CurrentThread.ManagedThreadId); } } }
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。