核心:
Thread th = new Thread(要执行的方法); th.IsBackground = true; th.Start(可以传入一个参数);
- 通过Thread调用的方法,只能接受一个参数,而且必须是object类型的参数。
- 为了传递更多的参数,可以通过类内封装的方式,调用类内的方法。
- Thread方法还有一个方法是Join:只有等线程结束,主线程才可继续。
参考代码:
class Program
{
static void Main(string[] args)
{
// 只能接受一个参数,并且必须是object类型的参数。
Thread th = new Thread(Method1);
th.IsBackground = true;
th.Start(100);
Console.WriteLine(Thread.CurrentThread.ManagedThreadId);
// 第二种方法:单独创建一个关于Thread的类。类内封装一个要执行的方法,然后将参数通过类内字段传递。
MyThread mt = new MyThread("xx.bt", "www.baidu.com");
Thread th2 = new Thread(mt.Download);
th2.Start();
Thread th3 = new Thread(Method1);
th3.Join();// 主线程中插入th3线程,只有当th3结束后,才继续往下执行。
}
static void Method1(object a)
{
Console.WriteLine(a + "开始下载..."+Thread.CurrentThread.ManagedThreadId);
Thread.Sleep(1000);
Console.WriteLine("下载结束。");
}
}
public class MyThread
{
public string _name;
public string _path;
public MyThread(string fileName, string filePath)
{
this._name = fileName;
this._path = filePath;
}
public void Download()
{
Console.WriteLine("开始下载" + _name);
Thread.Sleep(1000);
Console.WriteLine("下载结束。"+ _path);
}
}