C#多线程的几种实现方法

时间:2023-12-16 23:05:20

1.最简单的多线程

using System;
using System.Threading; namespace ThreadTest1
{
public class SimpleThread
{
public void Run()
{
Thread t1 = new Thread(new ThreadStart(this.ThreadFunc));
Thread t2 = new Thread(new ThreadStart(this.ThreadFunc));
t1.Start();
Thread.Sleep(1000);
t2.Start();
} private void ThreadFunc()
{
for (int i = 0; i < 100; i++)
{
Console.WriteLine(i);
Thread.Sleep(100);
}
}
}
}

2.可以传参数的多线程

using System;
using System.Threading; namespace ThreadTest1
{
class ThreadWithPara
{
public void Run()
{
Thread t1 = new Thread(ThreadFunc);
Thread t2 = new Thread(new ParameterizedThreadStart(ThreadFunc));
t1.Start("t1");
Thread.Sleep(1000);
t2.Start("t2");
} private void ThreadFunc(object obj)
{
for (int i = 0; i < 100; i++)
{
Console.WriteLine(i + obj.ToString());
Thread.Sleep(100);
}
}
}
}

3.自定义类的多线程

using System;
using System.Threading; namespace ThreadTest1
{
class MyThreadClass
{
private string data; public MyThreadClass(string data)
{
this.data = data;
} public void ThreadMain()
{
Console.WriteLine("Running in a thread,data: {0}", data);
}
} class MainClass
{
public void Run()
{
MyThreadClass mtc = new MyThreadClass("thread1");
Thread thread = new Thread(mtc.ThreadMain);
thread.Start();
}
}
}

4. 匿名方法实现的多线程

using System;
using System.Threading; namespace ThreadTest1
{
public class AnonymousThread
{
public void Run()
{
Thread t1 = new Thread(() => ThreadFunc("thread-1"));
t1.Start();
} private void ThreadFunc(string obj)
{
for (int i = 0; i < 100; i++)
{
Console.WriteLine(i + obj.ToString());
Thread.Sleep(100);
}
}
}
}

5.参考

C# 给多线程传参的三种方式