C#线程问题为什么在这里无限循环?

问题描述

|
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;

namespace ThreadExample
{
    public class Info
    {
        public int Counter;


        private static object _lock = new object();
        private List<Thread> ThreadList;

        public Info(int counter)
        {
            Counter = counter;

            ThreadList = new List<Thread>();

            ThreadList.Add(new Thread(ThreadBody));
            ThreadList.Add(new Thread(ThreadBody));

           ThreadList[0].Name = \"t1\";
           ThreadList[1].Name = \"t2\";

        }

        public void Start()
        {
            ThreadList.ForEach(t => t.Start(t.Name));
        }

        public void ThreadBody(object name)
        {
            while (Counter != 20)
            {
                lock (_lock)
                {
                    Counter++;

                    Console.WriteLine(\"Thread {0} : the value of the counter is {1}\",name.ToString(),Counter);
                }
            }



        }

    }
}


using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ThreadExample
{
    class Program
    {
        static void Main(string[] args)
        {
            Info info = new Info(0);
            info.Start();
        }
    }
}
如果锁只是锁计数器++   锁(_lock)                     {                         计数器++;                      }          我没有无限循环,但是如果锁如示例所示,它将运行无限循环     

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)