在我的應用程序具有低於類2個線程之間的同步中的一個。
- SynchornizingMethods講座>將由線程1和線程共享2.
- DemoClass1 - >通過螺紋簡稱1
- DemoClass2 - >由線程2
- SynchornizingDemo.Demo()簡稱 - >方法是程序的入口點。
預期輸出:
線程1(DemoClass1)和線程2(DemoClass2),直到這兩個線程完成它們的環在各自的XXXXRun()方法應該平行地延伸。
現狀:
程序,當我從我的應用程序調用SynchornizingDemo.Demo()只是掛起。
代碼:
public class SynchornizingMethods
{
static string SharedVariableString = string.Empty;
bool threadFlag = true;
public void Method1(int inputVal)
{
lock (this)
{
if (threadFlag == true)
{
try
{
Monitor.Wait(this);
}
catch (SynchronizationLockException SLE)
{
SharedVariableString += "\nMethod 1 : " + SLE.Message.ToString();
}
catch (ThreadInterruptedException TIE)
{
SharedVariableString += "\nMethod 1 : " + TIE.Message.ToString();
}
SharedVariableString += "\nMethod 1 : " + inputVal;
threadFlag = false;
}
Monitor.Pulse(this);
}
}
public void Method2(int inputVal)
{
lock (this)
{
if (threadFlag == false)
{
try
{
Monitor.Wait(this);
}
catch (SynchronizationLockException SLE)
{
SharedVariableString += "\nMethod 2 : " + SLE.Message.ToString();
}
catch (ThreadInterruptedException TIE)
{
SharedVariableString += "\nMethod 2 : " + TIE.Message.ToString();
}
SharedVariableString += "\nMethod 2 : " + inputVal;
threadFlag = true;
}
Monitor.Pulse(this);
}
}
public static void DisplayResult()
{
MessageBox.Show(SharedVariableString);
}
}
public class DemoClass1
{
SynchornizingMethods SyncMethodsObj;
public DemoClass1(SynchornizingMethods _SyncMethodsObj)
{
SyncMethodsObj = _SyncMethodsObj;
}
public void DemoThread1Run()
{
// Even Incrementor.
for (int lpCnt = 0; lpCnt <= 20; lpCnt += 2)
{
//Thread.Sleep(10);
SyncMethodsObj.Method1(lpCnt);
}
}
}
public class DemoClass2
{
SynchornizingMethods SyncMethodsObj;
public DemoClass2(SynchornizingMethods _SyncMethodsObj)
{
SyncMethodsObj = _SyncMethodsObj;
}
public void DemoThread2Run()
{
// Odd Incrementor.
for (int lpCnt = 1; lpCnt <= 20; lpCnt += 2)
{
//Thread.Sleep(10);
SyncMethodsObj.Method2(lpCnt);
}
}
}
public class SynchornizingDemo
{
public void Demo()
{
SynchornizingMethods SyncMethodsObj = new SynchornizingMethods();
DemoClass1 DemoClass1Obj = new DemoClass1(SyncMethodsObj);
DemoClass2 DemoClass2Obj = new DemoClass2(SyncMethodsObj);
try
{
Thread thread1Obj = new Thread(new ThreadStart(DemoClass1Obj.DemoThread1Run));
Thread thread2Obj = new Thread(new ThreadStart(DemoClass2Obj.DemoThread2Run));
thread1Obj.Start();
thread2Obj.Start();
thread1Obj.Join();
thread2Obj.Join();
}
catch (ThreadStateException TSE)
{
Debug.WriteLine(" Exception Raised SynchornizingDemo : " + TSE.Message.ToString());
}
catch (ThreadInterruptedException TIE)
{
Debug.WriteLine(" Exception Raised SynchornizingDemo : " + TIE.Message.ToString());
}
SynchornizingMethods.DisplayResult();
}
}
該代碼「看起來」不完整,當然不會被任何人編譯。你也在說「不按預期工作」 - 它如何工作,你會得到什麼結果。 – iandotkelly
@iandotkelly,是的,它完成的代碼只需要調用SynchornizingDemo.Demo()進行測試,這是我在第一篇文章中提到的,但修改該語句的人被刪除並導致混淆。我已經發布了下面的工作計劃。 – Sai