0
我學習揮發,聯鎖和鎖在C#中,寫了下面的代碼,而無需使用任何這些同步結構的打印奇數和偶數,我跑這個代碼幾次,總是給正確答案,爲什麼此代碼的工作,而不是崩潰
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace microsoft
{
class th2_odd_event
{
static int num = 1;
static bool guard = false;
public void init()
{
Thread th = new Thread(print_odd);
Thread th2 = new Thread(print_even);
th.Start();
th2.Start();
}
public static void print_odd()
{
while (true)
{
if (guard == false)
{
if (num % 2 != 0)
{
Console.WriteLine(num);
num++;
}
guard = true;
}
if (num > 20)
break;
}
}
public static void print_even()
{
while (true)
{
if (guard == true)
{
if (num % 2 == 0)
{
Console.WriteLine(num);
num++;
}
guard = false;
}
if (num > 20)
break;
}
}
}
代碼的工作原理?這是幸運的,兩個線程之間沒有衝突?我失去了一些東西......
謝謝拉賈! :) – Sandeep