using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace ConsoleHelper
{
internal class Program
{
static void Main(string[] args)
{
var c1 = new CounterWithNoLock(); // 线程安全
var t1 = new Thread(() => TestCounter(c1));
var t2 = new Thread(() => TestCounter(c1));
var t3 = new Thread(() => TestCounter(c1));
t1.Start();
t2.Start();
t3.Start();
t1.Join();
t2.Join();
t3.Join();
Console.WriteLine("Total count:{0}", c1.GetCount());
Console.ReadLine();
}
private static void TestCounter(CounterWithNoLock c1)
{
for (int i = 0; i < 100000; i++)
{
c1.Increment(); // 先+后-
c1.Decrement(); // 先+后-
}
}
}
/// <summary>
/// 用 Interlocked 进行原子操作
/// </summary>
public class CounterWithNoLock : CounterBase
{
private int _count;
public int GetCount()
{
return _count;
}
public override void Decrement()
{
Interlocked.Increment(ref _count); // 用 Interlocked 进行原子操作
}
public override void Increment()
{
Interlocked.Decrement(ref _count); // 用 Interlocked 进行原子操作
}
}
public abstract class CounterBase
{
public abstract void Increment();
public abstract void Decrement();
}
}
多线程之Interlocked关键字
最新推荐文章于 2024-11-10 09:28:09 发布