a.今天學到一個非常試用的lock
文法:
lock(expression) statement_block
expression代表你希望跟蹤的對象,通常是對象引用。一般地,如果你想保護一個類的執行個體,你可以使用this;如果你希望保護一個靜態變數(如互斥程式碼片段在一個靜態方法內部),一般使用類名就可以了。而statement_block就是互斥段的代碼,這段代碼在一個時刻內只可能被一個線程執行。 using System;
using System.Collections.Generic;
using System.Text;
using System.Threading;
namespace LockThread
{
internal class Account
{
int balance;
Random r = new Random();
internal Account(int _initial)
{
balance = _initial;
}
internal int Withdraw(int _amount)
{
if(balance < 0)
{
//如果balance<0則拋出異常
throw new Exception("Negative Balance");
}
//下面的代碼保證在當前線程修改balance的值完成之前
//不會有其他線程也執行這段代碼來修改balance的值
//因此,balance的值是不可能小於0的
lock(this)
{
Console.WriteLine("Current Thread:"+Thread.CurrentThread.Name);
//如果沒有lock關鍵字的保護,那麼可能在執行完if的條件判斷之後
//另外一個線程卻執行了balance=balance-amount修改了balance的值
//而這個修改對這個線程是不可見的,所以可能導致這時if的條件已經不成立了
//但是,這個線程卻繼續執行balance=balance-amount,所以導致balance可能小於0
if(balance >= _amount)
{
Thread.Sleep(5);
balance = balance -_amount;
return _amount;
} else{
return 0;//處理事務被拒絕
}
}
}
internal void DoTransactions()
{
for(int i = 0;i<100; i++)
Withdraw(r.Next(-50, 100));
}
}
class Program
{
static internal Thread[] threads = new Thread[10];
static void Main(string[] args)
{
Account acc = new Account(0);
for (int i = 0; i < 10; i++)
{
Thread t = new Thread(new ThreadStart(acc.DoTransactions));
t.Name = i.ToString();
threads[i] = t;
}
for (int i = 0; i < 10; i++)
{
threads[i].Start();
}
Console.ReadLine();
}
}
}
b.還有一個Moniter對象是用來監視對象的,
......
Queue oQueue=new Queue();
......
Monitor.Enter(oQueue);
......//現在oQueue對象只能被當前線程操縱了
Monitor.Exit(oQueue);//釋放鎖
上面表示oQueue這個對象只有一個線程可以操縱,只有當Mointor.Exit才可以被其它線程所操縱