所以我有这个程序试图建立两个不同的线程,thread1和thread2之间的通信。等待另一个线程
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
namespace Project1
{
class Class1
{
public static void thread1()
{
Console.WriteLine("1");
Console.WriteLine("t2 has printed 1, so we now print 2");
Console.WriteLine("t2 has printed 2, so we now print 3");
}
public static void thread2()
{
Console.WriteLine("t1 has printed 1, so we now print 1");
Console.WriteLine("t1 has printed 2, so we now print 2");
Console.WriteLine("t1 has printed 3, so we now print 3");
}
public static void Main() {
Thread t1 = new Thread(new ThreadStart(() => thread1()));
Thread t2 = new Thread(new ThreadStart(() => thread2()));
t1.Start();
t2.Start();
t2.Join();
t1.Join();
}
}
}
不过,我希望它发生,使得该行:
Console.WriteLine("1");
...最先被执行,而线程2只等待被执行这条线。那时,也只有这样才打印:该行打印
Console.WriteLine("t1 has printed 1, so we now print 1");
后,再然后才将这一行:
Console.WriteLine("t2 has printed 1, so we now print 2");
...得到印刷,等等。所以我想更改代码,使线程相互沟通,使线路得到印刷顺序:
Console.WriteLine("1"); // from t1
Console.WriteLine("t1 has printed 1, so we now print 1"); // from t2
Console.WriteLine("t2 has printed 1, so we now print 2"); // from t1
Console.WriteLine("t1 has printed 2, so we now print 2"); // from t2
Console.WriteLine("t2 has printed 2, so we now print 3"); // from t1
Console.WriteLine("t1 has printed 3, so we now print 3"); // from t2
我明白做什么锁,但它仅适用,如果两个不同的线程是运行在相同的功能上。但是,在这里,这两个函数是不同的,因此我不能在这里使用锁。
任何想法?
只是在锁记,因为我下面提到的,你的线程不需要处于相同的功能。只要在同一进程中运行,锁可用于同步线程**。如果您尝试同步不同进程中的线程(例如同步两个不同的程序),则需要使用Mutex。 – 2012-08-16 16:34:25