在C#中 Thread 类表示线程。
要在C#中启用多线程,需要构造Thread类。
构造Thread类有多种形式,有带参数的和不带参数的。
如下所示:
using System;
using System.Threading;namespace ConsoleApp1
{
class Program
{static void Main(string[] args)
{
output(“abc”);Thread t1 = new Thread(output1);
t1.Start();
}
static void output(string message)
{Console.WriteLine(message);
Console.WriteLine(Thread.CurrentThread.ManagedThreadId.ToString());
}static void output1()
{
Console.WriteLine(“test”);Console.WriteLine(Thread.CurrentThread.ManagedThreadId.ToString());
}}
}
Thread t1 = new Thread(output1); 初始化了一个不带参数的委托output1线程。
如下所示:
using System;
using System.Threading;namespace ConsoleApp1
{
class Program
{static void Main(string[] args)
{
output(“abc”);//不带参数的线程
Thread t1 = new Thread(output1);t1.Start();
//带参数的线程
Thread t2= new Thread(output);t2.Start(“sbd”);
}
static void output(object message)
{Console.WriteLine(message);
Console.WriteLine(Thread.CurrentThread.ManagedThreadId.ToString());
}static void output1()
{
Console.WriteLine(“test”);Console.WriteLine(Thread.CurrentThread.ManagedThreadId.ToString());
}}
}
Thread t2= new Thread(output);
t2.Start(“sbd”);
初始化了一个带参数的线程,该线程的委托类型可以是带参数的。
发表评论