そのため、2 つの異なるスレッド (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");
...最初に実行されますが、thread2 はこの行が実行されるのを待つだけです。そのときだけ、次のように出力されます。
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
ロックの機能は理解していますが、2 つの異なるスレッドが同じ関数で実行されている場合にのみ適用されます。ただし、ここでは 2 つの機能が異なるため、ここではロックを使用できません。
何か案は?