当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《当内部有循环时,锁定语句不起作用?》经验,为你挑选了1个好方法。

看到这段代码:

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();
    }

我希望m2m1开始执行之前必须从头到尾执行,反之亦然,因为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

我做错了什么?



1> tvanfosson..:

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

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

推荐阅读
mobiledu2402851173
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有