lock锁和monitor.enter锁
| | Lock(object)鎖的使用 |
using System;
using System.Threading;
namespace program
{
????class wangjun
????{
????????public static string buff = "0";
????????public const int ab = 1000000;
????????private object mylock = new object();
????????static void Main(string[] args)
????????{
????????????wangjun wj = new wangjun();
????????????Thread th = new Thread(new ThreadStart(wj.xuan1));
????????????th.Start();
????????????Thread th2 = new Thread(new ThreadStart(wj.xuan2));
????????????th2.Start();
????????????th.Join();
????????????th2.Join();
????????????Console.WriteLine("結(jié)果是:{0}",buff);
????????}
????????public void xuan1()
????????{
????????????for (int i = 0; i < ab/2; i++)
????????????{
????????????????lock (mylock)
????????????????{
????????????????????buff = (long.Parse(buff) + i).ToString();
????????????????}
????????????}
????????}
????????public void xuan2()
????????{
????????????for (int i = ab/2; i <= ab; i++)
????????????{
????????????????lock (mylock)
????????????????{
????????????????????buff = (long.Parse(buff) + i).ToString();
????????????????}
????????????}
????????}
????}
}
Monitor.enter(object)的使用
using System;
using System.Threading;
namespace program
{
????class wangjun
????{
????????public static string buff = "0";
????????public const int ab = 1000000;
????????private object mylock = new object();
????????static void Main(string[] args)
????????{
????????????wangjun wj = new wangjun();
????????????Thread th = new Thread(new ThreadStart(wj.xuan1));
????????????th.Start();
????????????Thread th2 = new Thread(new ThreadStart(wj.xuan2));
????????????th2.Start();
????????????th.Join();
????????????th2.Join();
????????????Console.WriteLine("結(jié)果是:{0}",buff);
????????}
????????public void xuan1()
????????{
????????????for (int i = 0; i < ab/2; i++)
????????????{
????????????????Monitor.Enter(mylock);
????????????????try
????????????????{
????????????????????buff = (long.Parse(buff) + i).ToString();
????????????????}
????????????????finally
????????????????{
????????????????????Monitor.Exit(mylock);
????????????????}
????????????}
????????}
????????public void xuan2()
????????{
????????????for (int i = ab/2; i <= ab; i++)
????????????{
????????????????Monitor.Enter(mylock);
????????????????try
????????????????{
????????????????????buff = (long.Parse(buff) + i).ToString();
????????????????}
????????????????finally
????????????????{
????????????????????Monitor.Exit(mylock);
????????????????}
????????????}
????????}
????}
}
總結(jié)
以上是生活随笔為你收集整理的lock锁和monitor.enter锁的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: C# GDI+ 绘图
- 下一篇: AVS解码器在DSP平台上的优化