在调用此方法的线程上引发 ThreadAbortException,以开始终止此线程的过程。调用此方法通常会终止线程。
阻塞调用线程,直到某个线程终止时为止。
{
Thread ThrTest1 = new Thread(new ThreadStart(WriteLine1));
Thread ThrTest2 = new Thread(new ThreadStart(WriteLine2));
ThrTest1.Start();
ThrTest2.Start();
}
public static void WriteLine1()
{
for (int i = 0; i < 20; i++)
{
if (i == 10)
{
ThrTest2.Join();
}
Console.ForegroundColor = ConsoleColor.Blue;
Console.WriteLine(i.ToString() + "WriteLine1");
Thread.Sleep(500);
}
}
public static void WriteLine2()
{
for (int i = 0; i < 20; i++)
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(i.ToString() + "WriteLine2");
Thread.Sleep(500);
}
}
如图所示:
在ThrTest1中用了ThrTest2.Join()语句块,所以是走线程ThrTest1时阻塞了,用ThrTest2.Join()所以让线程ThrTest2走,直到终止,线程ThrTest1才解除阻塞,这又可看成“他杀”,对比Abort的“自杀”。
Monitor.Pulse(this);通知等待队列中的线程锁定对象状态的更改(只更改下一个而不是所有(?),是不是,是吧)
Monitor.Wait(this);释放对象上的锁并阻止当前线程,直到它重新获取该锁
使用monitor类容易造成混乱,例如在消费者生产者问题中,如果有两个生产者一个消费者的话,建议使用lock,,个人陋见,贻笑大方,因为我水平不高很容易搞乱
lock:Monitor 类通过向单个线程授予对象锁来控制对对象的访问。
对象锁提供限制访问代码块(通常称为临
static void Main()
{
TwoThread tt = new TwoThread();
ThreadStart th1s = new ThreadStart(tt.Method1);
Thread th1 = new Thread(th1s);
th1.Start();
Thread th3 = new Thread(th3s);
th3.Start(1111111111);
Thread th2 = new Thread(th2s);
th2.Start();
void Method3(object o)
{
for (int i = 0; i < 1000; i++)
{
lock (this)
{
Console.WriteLine(i + o.ToString());
}
}
void Method2()
{
for (int i = 0; i < 1000; i++)
{
lock (this)
{
Console.WriteLine(i);
}
}
}
void Method1()
{
for (int i = 0; i < 1000; i++)
{
lock (this)
{
Console.ForegroundColor = ConsoleColor.Green;
Console.WriteLine(i);
}
}