【進程線程與同步】5.4 System.Threading.Interlocked 為多個線程共享的變量提供原子操作
using System;
using System.Threading;
internal class Program
{
private static long _counter = 1;
private static void Main()
{
//下麵程序顯示兩個線程如何並發訪問一個名為counter的整形變量,一個線程讓他遞增5次,一個讓他遞減5次
Console.WriteLine("原始值:{0}", _counter);
var t1 = new Thread(F1);
var t2 = new Thread(F2);
t1.Start();
t2.Start();
t1.Join();
t2.Join();
Console.WriteLine("最終值:{0}", _counter);
Console.Read();
}
private static void F1()
{
for (int i = 0; i < 5; i++)
{
Interlocked.Increment(ref _counter);//原子性操作
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ff") + " 方法1:counter++:{0}", _counter);
Thread.Sleep(10);
}
}
private static void F2()
{
for (int i = 0; i < 5; i++)
{
Interlocked.Decrement(ref _counter);//原子性操作
Console.WriteLine(DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss:ff") + " 方法2:counter--:{0}", _counter);
Thread.Sleep(10);
}
}
}
最後更新:2017-04-03 16:59:42