线程其实就是操作系统中提到更加小的运行单元,比如一个进程可以存在多个线程,线程的执行不一定按顺序,并且从外部看来是同时进行的。
我们举一个线程的一般定义,当然在定义之前需要先导入线程命名空间 using System.Threading;
class Demo1 { public void Method_1() { for (int i = 0; i < 100; i++) { Console.WriteLine("我是线程1"); } } public void Method_2() { for (int i = 0; i < 100; i++) { Console.WriteLine("我是线程2"); } } public void Test() { Thread t1 = new Thread(Method_1); t1.Start(); Thread t2 = new Thread(Method_2); t2.Start(); } static void Main(string[] args) { Demo1 obj = new Demo1(); obj.Test(); }
如果对于某一个线程比较简单,可以使用Lamda表达式
public void Test1() { Thread t1 = new Thread( () => { for (int i = 0; i < 100; i++) { Console.WriteLine("我是线程1"); } } ); t1.Start(); Thread t2 = new Thread( () => { for (int i = 0; i < 100; i++) { Console.WriteLine("我是线程2"); } } ); t2.Start(); } static void Main(string[] args) { Demo1 obj = new Demo1(); obj.Test1(); }
线程中的方法不止上文的,它本身有3个重载方法,接下来是线程传递一个参数的例子:
public void LoadDownFile(object fileName) { Console.WriteLine("文件名:"+fileName.ToString()); Console.WriteLine("文件下载:"+Thread.CurrentThread.ManagedThreadId); Thread.Sleep(1000); Console.WriteLine("下载完毕"); } public void Test2() { Thread t = new Thread(LoadDownFile); t.Start("abc.mov"); }
线程传递多个参数,在构造函数传递多个参数。
public class ThreadTest { private string _FilePath; private string _FileName; public ThreadTest(string filePath,string fileName) { _FilePath = filePath; _FileName = fileName; } public void DownLoadFile() { Console.WriteLine("开始下载"+_FileName+"//"+_FilePath); Thread.Sleep(3000); Console.WriteLine("下载完毕"); } }
public void Test3() { ThreadTest thObj = new ThreadTest("伤心的人别听慢歌","你呀你我说你什么好"); Thread t1 = new Thread(thObj.DownLoadFile); t1.Start(); }
原文:https://www.cnblogs.com/Optimism/p/10502795.html