3、线程同步

  线程同步的方法有很多很多种volatile、Lock、InterLock、Monitor、Mutex、ReadWriteLock...

  这里用lock说明问题:在哪里同步,用什么同步,同步谁?

  首先感受下不同步会出现的问题:

  代码是下面的代码去掉lock块。

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using System.Threading;
    
    namespace 多线程3_同步2
    {
        class Program
        {
            static object obj = new object();//同步用
    
            static int balance = 500;
    
            static void Main(string[] args)
            {
                Thread t1 = new Thread(new ThreadStart(Credit));
                t1.Start();
    
                Thread t2 = new Thread(new ThreadStart(Debit));
                t2.Start();
    
                Console.ReadKey();
            }
    
            static void Credit()
            {
                for (int i = 0; i < 15; i++)
                {
                    lock (obj)
                    {
                        balance += 100;
                        Console.WriteLine("After crediting,balance is {0}", balance);
                    }
                }
            }
            static void Debit()
            {
                for (int i = 0; i < 15; i++)
                {
                    lock (obj)
                    {
                        balance -= 100;
                        Console.WriteLine("After debiting,balance is {0}", balance);
                    }
                }
            }
        }
    }

  小结:多线程调用函数是这样。在Winform中,控件绑定到特定的线程,从另一个线程更新控件,不应该直接调用该控件的成员,这个非常有用。