前面說過
C#提供了一個關鍵字lock
lock(expression) statement_block
expression代表你希望跟蹤的對象
如果你想保護一個類的實例
而statement_block就是互斥段的代碼
下面是一個使用lock關鍵字的典型例子
示例如下
using System;
using System
namespace ThreadSimple
{
internal class Account
{
int balance;
Random r = new Random();
internal Account(int initial)
{
balance = initial;
}
internal int Withdraw(int amount)
{
if (balance <
{
//如果balance小於
throw new Exception(
}
//下面的代碼保證在當前線程修改balance的值完成之前
//不會有其他線程也執行這段代碼來修改balance的值
//因此
lock (this)
{
Console
//如果沒有lock關鍵字的保護
//另外一個線程卻執行了balance=balance
//而這個修改對這個線程是不可見的
//但是
if (balance >= amount)
{
Thread
balance = balance
return amount;
}
else
{
return
}
}
}
internal void DoTransactions()
{
for (int i =
Withdraw(r
}
}
internal class Test
{
static internal Thread[] threads = new Thread[
public static void Main()
{
Account acc = new Account (
for (int i =
{
Thread t = new Thread(new ThreadStart(acc
threads[i] = t;
}
for (int i =
threads[i]
for (int i =
threads[i]
Console
}
}
}
From:http://tw.wingwit.com/Article/program/net/201311/15368.html