ITPub博客

首页 > Linux操作系统 > Linux操作系统 > lock锁和monitor.enter锁

lock锁和monitor.enter锁

原创 Linux操作系统 作者:taogchan 时间:2013-09-16 17:56:17 0 删除 编辑

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

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

来自 “ ITPUB博客 ” ,链接:http://blog.itpub.net/22392018/viewspace-772796/,如需转载,请注明出处,否则将追究法律责任。

上一篇: 记录日志文件
请登录后发表评论 登录
全部评论

注册时间:2009-08-28

  • 博文量
    200
  • 访问量
    1188359