接上文 多线程编程学习笔记-基础(一)
接上文 多线程编程学习笔记-基础(二)
九、向线程传递参数
1.代码如下。
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; //引入线程 using System.Diagnostics; namespace ThreadConsoleApp { class Program { static void Main(string[] args) { Console.WriteLine("开始,给线程传参数"); var fore = new ThreadBackground(10); Thread t = new Thread(fore.CountNumber); t.Name = "线程1"; //启动线程 t.Start(); t.Join(); Console.WriteLine("----------------------------"); var t2 = new Thread(Count); t2.Name = "线程2"; t2.Start(8); t2.Join(); Console.WriteLine("----------------------------"); var t3 = new Thread(()=>CountNumber(12)); t3.Name = "线程3"; t3.Start(); t3.Join(); Console.WriteLine("----------------------------"); int i = 10; var t4 = new Thread(() => PrintNumber(i)); t4.Name = "线程4"; i = 20; var t5 = new Thread(() => PrintNumber(i)); t5.Name = "线程5"; t4.Start(); t5.Start(); Console.Read(); } static void CountNumber(int cnt) { for (int i = 0; i < cnt; i++) { Thread.Sleep(500); Console.WriteLine(string.Format(" {0} 打印 {1,11} 数字", Thread.CurrentThread.Name, i.ToString("N0"))); } } static void Count(object cnt) { CountNumber((int)cnt); } static void PrintNumber(int num) { Console.WriteLine(string.Format(" {0} 打印 {1,11} 数字", Thread.CurrentThread.Name, num.ToString("N0"))); } } }
2.结果如下图。
线程1,我们通过实例化对象来进行参数传递。
线程2,我们使用Thread.Start()来传递参数,不过此方法只接收单个参数,而且是对象类型。
线程3,我们使用lambda表达式进行参数传递,lambda表达式定义了一个不属于任何类的方法,同时该方法调用了我们实际要执行的方法,同时传递参数给线程。
线程4与线程5,则是显示了使用lambda表达式进行参数传递的一个问题,即当多个lambda表达式共用一个变量时,它们会共享这个变量的值。如图中线程4与线程5所显示,没有打印10,只打印了20。
十、使用lock锁定操作
1.代码如下
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; //引入线程 using System.Diagnostics; namespace ThreadConsoleApp { class Program { static void Main(string[] args) { Console.WriteLine("开始,给线程加锁"); var c = new Counter(); Thread t = new Thread(()=>Count(c)); var t3 = new Thread(() => Count(c)); var t2 = new Thread(() => Count(c)); t.Name = "线程1"; //启动线程 t.Start(); t2.Name = "线程2"; t2.Start(); t3.Name = "线程3"; t3.Start(); t.Join(); t2.Join(); t3.Join(); Console.WriteLine(string.Format("没有加锁的多线程总计:{0}",c.Count)); Console.WriteLine("----------------------------"); var c1 = new CounterLock(); var t4 = new Thread(() => Count(c1)); t4.Name = "线程4"; var t5 = new Thread(() => Count(c1)); t5.Name = "线程5"; var t6 = new Thread(() => Count(c1)); t6.Name = "线程6"; t4.Start(); t5.Start(); t6.Start(); t4.Join(); t5.Join(); t6.Join(); Console.WriteLine(string.Format("加锁的多线程总计:{0}", c1.Count)); Console.Read(); } static void Count(CountBase cnt) { for (int i = 0; i < 100000; i++) { cnt.Incerement(); cnt.Dncerement(); }