复制代码 代码如下:
var objLock = new Object();
var thread1 = new Thread(() =>
{
lock (objLock)
{
AccessResource();
}
});
var thread2 = new Thread(() =>
{
lock (objLock)
{
AccessResource();
}
});
复制代码 代码如下:
var mutex = new Mutex(false, "name");
var thread1 = new Thread(() =>
{
try
{
mutex.WaitOne();
AccessResource();
}
finally
{
mutex.ReleaseMutex();
}
});
var thread2 = new Thread(() =>
{
try
{
mutex.WaitOne();
AccessResource();
}
finally
{
mutex.ReleaseMutex();
}
});
复制代码 代码如下:
using System;
using System.Collections.Generic;
using System.Threading;
namespace ThreadCancle
{
public class ProducerConsumer2
{
public static void Main()
{
var autoResetEvent = new AutoResetEvent(false);
var queue = new Queue<int>();
var producterThread = new Thread(() =>
{
var rand = new Random();
while (true)
{
var value = rand.Next(100);
lock (queue)
{
queue.Enqueue(value);
}
Thread.Sleep(rand.Next(400, 1200));
Console.WriteLine("产生了数据{0}。", value);
autoResetEvent.Set();
}
});
var consumerThread = new Thread(() =>
{
while (true)
{
autoResetEvent.WaitOne();
int value = 0;
bool hasValue = true;
while (hasValue)
{
lock (queue)
{
hasValue = (queue.Count > 0);
if (hasValue)
{
value = queue.Dequeue();
}
}
Thread.Sleep(800);
Console.WriteLine("处理了数据{0}。", value);
}
}
});
producterThread.Start();
consumerThread.Start();
Console.ReadLine();
}
}
}
新闻热点
疑难解答
图片精选