1、线程初探

static void Main(string[] args)
{
  Console.WriteLine("Begin");

  Thread t1 = new(() => PrintNumberWithDelay("A"));
  t1.Join();// 让主线程等待,子线程执行完后再执行下面的代码。
  t1.Priority = ThreadPriority.Lowest;

  Thread t2 = new(() => PrintNumber("B"));
  t2.Priority = ThreadPriority.Highest;// 优先级高
  t2.IsBackground = true;// 后台执行,true 随着主线程的退出而退出

  t1.Start();
  t2.Start();
  PrintNumber("C");
}

static void PrintNumber(string n)
{
  Console.WriteLine($"Starting -> {n}");
  for (int i = 1; i <= 10; i++)
  {
    Console.WriteLine($"{n}{i}");
  }
}

static void PrintNumberWithDelay(string n)
{
  Console.WriteLine($"Starting -> {n}");
  for (int i = 1; i <= 10; i++)
  {
    Thread.Sleep(TimeSpan.FromSeconds(2));
    Console.WriteLine($"{n}{i}");
  }
}

  2、简单加锁

static int number = 0;
static void Main(string[] args)
{
  Console.WriteLine("Begin");

  Thread t1 = new(() => Add("A"));
  Thread t2 = new(() => Add("B"));

  t1.Start();
  t2.Start();
}

private readonly static object _syncRoot = new();

static void Add(string name)
{
  for (int i = 0; i < 100000; i++)
  {
    AddNumberLock();
  }
  Console.WriteLine($"{name}{number}");
}

static void AddNumber()
{
  number++;
}

static void AddNumberLock()
{
  lock (_syncRoot)
  {
    number++;
  }
}

  3、死锁

static void Main(string[] args)
{
  Console.WriteLine("Begin");
  object lock1 = new();
  object lock2 = new();

  new Thread(() => LockTooMuch("A", lock1, lock2)).Start();

  lock (lock2)
  {
    Console.WriteLine($"C.lock2");
    Thread.Sleep(1000);
    Console.WriteLine("Monitor.TryEnter allows not to get stuck, returning false after a specified timeout is elapsed");
    if (Monitor.TryEnter(lock1, TimeSpan.FromSeconds(5)))
    {
      Console.WriteLine("Acquired a protected resource succesfully");
    }
    else
    {
      Console.WriteLine("Timeout acquirting a resource!");
    }
    Console.WriteLine($"C.unlock2");
  }

  new Thread(() => LockTooMuch("B", lock1, lock2)).Start();

  lock (lock2)
  {
    Console.WriteLine($"D.lock2");
    Console.WriteLine("This will be a deadlock!");
    Thread.Sleep(1000);
    lock (lock1)
    {
      Console.WriteLine($"D.lock1");
      Console.WriteLine("Acquired a protected resource succesfully");
      Console.WriteLine($"D.unlock1");
    }
    Console.WriteLine($"D.unlock2");
  }
}

static void LockTooMuch(string name, object lock1, object lock2)
{
  lock (lock1)
  {
    Console.WriteLine($"{name}.lock1");
    Thread.Sleep(1000);
    lock (lock2)
    {
      Console.WriteLine($"{name}.lock2");
      Thread.Sleep(10);
      Console.WriteLine($"{name}.unlock2");
    }
    Console.WriteLine($"{name}.unlock1");
  }
}

  4、



  5、



  6、



  7、



  8、



  ======================、

static int accountNumberA = 100;// A 的账号金额
static int accountNumberB = 100;// B 的账号金额
static int accountNumberC = 100;// C 的账号金额

private readonly static object _syncRootA = new();
private readonly static object _syncRootB = new();
private readonly static object _syncRootC = new();
private readonly static object _syncRootOperation = new();


/// 
/// 付款
/// 
/// 付款方 名称
/// 收款方 名称
public static void TransferToSomeOne(string payerAccountName, string payeeAccountName, int amount)
{
  string msg = $"{payerAccountName} transfer {payeeAccountName}";
  Operation(payerAccountName, -amount);
  Operation(payeeAccountName, amount);
  Console.WriteLine($"{msg} result A:{accountNumberA},B:{accountNumberB},C:{accountNumberC}");
}

/// 
/// 计算
/// 
/// 
/// 
public static void Operation(string payerAccountName, int amount)
{
  lock (_syncRootOperation)
  {
    Console.WriteLine($"Operation.lock");
    if (payerAccountName == "A")
    {
      lock (_syncRootA)
      {
        Console.WriteLine($"A.lock");
        Thread.Sleep(2000);
        accountNumberA += amount;
        Console.WriteLine($"A.unlock");
      }
    }

    if (payerAccountName == "B")
    {
      lock (_syncRootB)
      {
        Console.WriteLine($"B.lock");
        Thread.Sleep(2000);
        accountNumberB += amount;
        Console.WriteLine($"B.unlock");
      }
    }

    if (payerAccountName == "C")
    {
      lock (_syncRootC)
      {
        Console.WriteLine($"C.lock");
        Thread.Sleep(2000);
        accountNumberC += amount;
        Console.WriteLine($"C.unlock");
      }
    }

    Console.WriteLine($"Operation.unlock");
  }
}



static void Main(string[] args)
{
  Console.WriteLine("Begin");

  Thread t1 = new(() => TransferToSomeOne("B", "C", 10));
  Thread t2 = new(() => TransferToSomeOne("C", "A", 10));
  t1.Priority = ThreadPriority.Highest;
  t1.Start();

  t2.Priority = ThreadPriority.Lowest;
  t2.Start();
}