永发信息网

Monitor.Enter()有什么用???与LOCK()方法有什么区别??分别在什么时候用??谢谢大侠

答案:2  悬赏:50  手机版
解决时间 2021-02-28 11:58
  • 提问者网友:末路
  • 2021-02-27 17:18
Monitor.Enter()有什么用???与LOCK()方法有什么区别??分别在什么时候用??谢谢大侠
最佳答案
  • 五星知识达人网友:有你哪都是故乡
  • 2021-02-27 17:56
Monitor.enter(object)与线程同步锁lock(object) 的使用

一、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("结果是:{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);
}
}
}
}
}

二、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("结果是:{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();
}
}
}
}
}

希望以上可以帮到您!
全部回答
  • 1楼网友:归鹤鸣
  • 2021-02-27 18:59
可以私聊我~
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯