所以我有這個程序試圖建立兩個不同的線程,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