加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 当内部有循环时,锁定语句不起作用?

发布时间:2020-12-15 19:54:20 所属栏目:百科 来源:网络整理
导读:看到这段代码: public class multiply{ public Thread myThread; public int Counter { get; private set; } public string name { get; private set; } public void RunConsolePrint() { lock(this) { RunLockCode("lock"); } } private void RunLockCode(
看到这段代码:

public class multiply
{
    public Thread myThread;
    public int Counter
    {
        get;
        private set;
    }
    public string name
    {
        get;
        private set;
    }

    public void RunConsolePrint()
    {

        lock(this)
        {
        RunLockCode("lock");
        }


    }

    private void RunLockCode(string lockCode)
    {
        Console.WriteLine("Now thread "+lockCode+" " + name + " has started");
        for (int i = 1; i <= Counter; i++)
        {
            Console.WriteLine(lockCode+" "+name + ": count has reached " + i + ": total count is " + Counter);
        }
        Console.WriteLine("Thread " + lockCode + " " + name + " has finished");
    }
    public multiply(string pname,int pCounter)
    {
        name = pname;
        Counter = pCounter;
        myThread = new Thread(new ThreadStart(RunConsolePrint));
    }

}

这是测试运行代码:

static void Main(string[] args)
    {
        int counter = 50;

        multiply m2 = new multiply("Second",counter);
        multiply m1 = new multiply("First",counter);
        m1.myThread.Start();
        m2.myThread.Start();
        Console.ReadLine();
    }

我希望m2必须在m1开始执行之前从头到尾执行,反之亦然,因为lock语句.但是我发现的结果是首先锁定锁定而第二锁定是混合在一起,即类似这样的东西

Now thread lock First has started
Now thread lock Second has started
lock First: Count has reached 1: total count is 50
lock First: Count has reached 2: total count is 50
lock Second: Count has reached 1: total count is 50

我做错了什么?

解决方法

代码的每个实例都锁定在不同的对象上.您的锁对象需要在所有实例之间共享 – 使其成为静态类变量.

private static object syncRoot = new object();
public void RunConsolePrint()
{
    lock(syncRoot)
    {
         RunLockCode("lock");
    }    
}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读