zoukankan      html  css  js  c++  java
  • 多线程小记

    一、不加锁,多个线程同时执行时,导致资源冲突

     
    Thread t1 = new Thread(ThreadTest.ThreadNotThread);
    Thread t2 = new Thread(ThreadTest.ThreadNotThread);
    Thread t3 = new Thread(ThreadTest.ThreadNotThread);
    Thread t4 = new Thread(ThreadTest.ThreadNotThread);
    
    t1.Start();
    t2.Start();
    t3.Start();
    t4.Start();
    
    Console.ReadLine();
    
        class ThreadTest
        {
            public static int num = 10;
          
            /// <summary>
            /// 线程未加锁,导致读取资源异常
            /// 多个线程并行执行
            /// </summary>
            public static void ThreadNotThread()
            {
                while (true)
                {
                    if (num > 0)
                    {
                        Thread.Sleep(1000);
                        Console.WriteLine("nums:" + num--);    
                    }
                }
            }
        }
    
        
     
    二、加锁,多个线程同时执行时,依次执行,不会导致资源冲突

    Thread t2 = new Thread(ThreadTest.ThreadSyncThread);
    Thread t3 = new Thread(ThreadTest.ThreadSyncThread);
    Thread t4 = new Thread(ThreadTest.ThreadSyncThread);
    
    t1.Start();
    t2.Start();
    t3.Start();
    t4.Start();
    
    class ThreadTest
        {
            public static int num = 10;
    
            /// <summary>
            /// 线程加锁,导致读取资源正常
            /// 一个线程一个线程的执行
            /// lock("")这里的""表示一个对象,每个对象都存在一个标志位,0和1,一个线程运行同步块时先检查对象标志位
            /// 如果为0则表明同步块中存在其它线程在运行。这是该线程就处于就绪状态,直到处于同步块中的线程执行完成为止
            /// </summary>
            public static void ThreadSyncThread()
            {
                while (true)
                {
                    lock ("")
                    {
                        if (num > 0)
                        {
                            Thread.Sleep(1000);
                            Console.WriteLine("nums:" + num--);
                        }
                    }
                }
            }
        }    
  • 相关阅读:
    2019 SDN上机第7次作业
    第01组 Beta冲刺(4/5)
    第01组 Beta冲刺(3/5)
    第01组 Beta冲刺(2/5)
    第01组 Beta冲刺(1/5)
    2019 SDN上机第6次作业
    2019 SDN上机第5次作业
    SDN课程阅读作业(2)
    第01组 Alpha事后诸葛亮
    第01组 Alpha冲刺(6/6)
  • 原文地址:https://www.cnblogs.com/gossip/p/4501791.html
Copyright © 2011-2022 走看看