using System.Threading;
namespace 测试
{
class 多线程
{
//public delegate void ThreadStart();//两个线程代理的原形
//public delegate void ParameterizedThreadStart(Object obj);
public static void Main()
{
ThreadStart st = new ThreadStart(print);//创建一个线程委托 不带参数
ParameterizedThreadStart pts = new ParameterizedThreadStart(print); //创建一个线程委托 带参数
Thread th = new Thread(st);//创建一个线程 th
Thread th1 = new Thread(pts);//创建一个线程 th1
th.Start();//启动th线程
th.Join(); //等待th线程执行完
Data da = new Data(20, "Jin");//实例化一个参数Data由下面定义的
th1.Start(da);//启动th1线程并且传入参数
Console.WriteLine("其他事情!");
Console.Read();
}
//lock的参数 最佳做法是定义 private 对象来锁定, 或 private static 对象变量来保护所有实例所共有的数据。
//上面一段话引自MSDN
private static Object thisLock = new Object();
public static void print()
{
lock (thisLock)//互斥锁
{
for (int i = 0; i <= 100; i++)
{
Console.WriteLine(i);
}
}
}
public static void print(Object o)
{
Data da = (Data)o;
Console.WriteLine(da.name);
for (int i = 0; i <= da.max; i++)
Console.WriteLine(i);
}
}
//作为参数传递的类
public struct Data
{
public int max;
public string name;
public Data(int _max, string _name)
{
max = _max;
name = _name;
}
}
}