首页 新闻 赞助 找找看

C#锁的问题

0
悬赏园豆:5 [已解决问题] 解决于 2016-05-24 10:09

我想实现把一个对象锁定当执行完操作的时候解锁,在执行此操作过程中其他线程不允许读写此对象,一下是代码.但是发现无法实现想要的功能,请大家指教

 

    public class Test
    {
        static Test _temp = new Test();
        public object X { get; set; }
        public static void Get(object n)
        {
            lock (_temp)
            {

                Console.WriteLine(string.Format("{0}__X初始值为:{1}", Thread.CurrentThread.Name, _temp.X));
                Console.WriteLine(string.Format("{0}__传入值为:{1}", Thread.CurrentThread.Name, n));
                _temp.X = n;
                Thread.Sleep(8);
                Console.WriteLine(string.Format("{0}__赋值完毕为:{1}", Thread.CurrentThread.Name, _temp.X));
                Console.WriteLine("===============");
            }
        }

        public static void SetValue(object n)
        {
            _temp.X = n;
        }
    }

    class Program
    {
        static void Main(string[] args)
        {
            Thread[] thds = new Thread[10];
            for (int i = 0; i < 10; i++)
            {
                thds[i] = new Thread(new ParameterizedThreadStart(Test.Get));
                thds[i].Name = "thread" + i;
            }
            Thread[] thds2 = new Thread[10];
            for (int i = 0; i < 10; i++)
            {
                thds2[i] = new Thread(new ParameterizedThreadStart(Test.SetValue));
            }
            Random ran = new Random();
            for (int i = 0; i < 10; i++)
            {
                thds[i].Start(i);
                thds2[i].Start(ran.Next(100, 1000));
            }


            Console.Read();
        }
    }
bird man的主页 bird man | 初学一级 | 园豆:4
提问于:2016-05-24 09:43
< >
分享
最佳答案
0

逻辑问题

 

Get的锁没问题,主要是SetValue

收获园豆:5
Yu | 专家六级 |园豆:12980 | 2016-05-24 09:52

谢谢,懂了

bird man | 园豆:4 (初学一级) | 2016-05-24 10:09
其他回答(1)
0
private static object _locker = new object();

lock(_locker)
{

}

 

心怀宇宙 | 园豆:643 (小虾三级) | 2016-05-24 10:16
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册