美文网首页
C#线程和锁的例子

C#线程和锁的例子

作者: 万金流 | 来源:发表于2019-03-06 13:40 被阅读0次

static balance b1;

        static int f;

        static void Main(string[] args)

        {

            b1 = new balance();

            b1.b = 1000;

            Thread t1 = new Thread(new ThreadStart(add));

            Thread t2 = new Thread(new ThreadStart(sub));

            f = 1;

            t1.Start();

            t2.Start();

            Console.Read();

        }

        public static void add()

        {

            for (int i = 0; i < 1000; i++)

            {

                //lock (b1)

                {

                    if (f==-1)

                    {

                        Console.Write("add\n");

                        f = 1;

                    }

                    Console.Write(++b1.b+",");

                }

            }

        }

        public static void sub()

        {

            for (int i = 0; i < 1000; i++)

            {

                //lock (b1)

                {

                    if(f==1)

                    {

                        Console.Write("sub\n");

                        f = -1;

                    }

                    Console.Write(--b1.b+",");

                }

            }

        }

结果:不使用lock,加减处不平滑。

相关文章

网友评论

      本文标题:C#线程和锁的例子

      本文链接:https://www.haomeiwen.com/subject/sxptpqtx.html