.net Lock(this),Lock(obj),Lock("string") console app demo,线程安全
{
static object obj = new object();
static int balance = 500;
static void Main(string[] args)
{
//todo with lock,Safe thread
//Thread t1 = new Thread(new ThreadStart(Credit));
//t1.Start();
//Thread t2 = new Thread(() => Debit());
//t2.Start();
//todo without lock,thread not safty
//Thread t1 = new Thread(new ThreadStart(CreditNoLock));
//t1.Start();
//Thread t2 = new Thread(() => DebitNoLock());
//t2.Start();
//todo new instance,lock (this---context),Lock Failed
//var account = new Account();
//Thread t1 = new Thread(new ThreadStart(account.Credit));
//t1.Start();
//var account2 = new Account();
//Thread t2 = new Thread(() => account2.Debit());
//t2.Start();
//todo new instance,lock (obj-syncRoot),Lock Successed
var account = new Account();
Thread t1 = new Thread(new ThreadStart(account.CreditLockObj));
t1.Start();
var account2 = new Account();
Thread t2 = new Thread(() => account2.DebitLockObj());
t2.Start();
//todo 结论!! lock(this)只对当前instance有效,lock(obj)安全,lock("string字符串")无意义
Console.ReadKey();
}
static void Credit()
{
lock (obj)
{
for (int i = 0; i < 15; i++)
{
Thread.Sleep(500);
balance += 100;
Console.WriteLine("After crediting,balance is {0}", balance);
}
}
}
private static void Debit()
{
lock (obj)
{
for (int i = 0; i < 15; i++)
{
Thread.Sleep(500);
balance -= 100;
Console.WriteLine("After debiting,balance is {0}", balance);
}
}
}
static void CreditNoLock()
{
for (int i = 0; i < 15; i++)
{
Thread.Sleep(1000);
balance += 100;
Console.WriteLine("After crediting,balance is {0}", balance);
}
}
private static void DebitNoLock()
{
for (int i = 0; i < 15; i++)
{
Thread.Sleep(1000);
balance -= 100;
Console.WriteLine("After debiting,balance is {0}", balance);
}
}
}
public class Account
{
static int balance = 500;
static object obj = new object();
public void Credit()
{
lock (this)
{
for (int i = 0; i < 5; i++)
{
Thread.Sleep(1000);
balance -= 100;
Console.WriteLine("After debiting,balance is {0}", balance);
}
}
}
public void Debit()
{
lock (this)
{
for (int i = 0; i < 5; i++)
{
Thread.Sleep(1000);
balance += 100;
Console.WriteLine("After debiting,balance is {0}", balance);
}
}
}
public void CreditLockObj()
{
lock (obj)
{
for (int i = 0; i < 5; i++)
{
Thread.Sleep(1000);
balance -= 100;
Console.WriteLine("After debiting,balance is {0}", balance);
}
}
}
public void DebitLockObj()
{
lock (obj)
{
for (int i = 0; i < 5; i++)
{
Thread.Sleep(1000);
balance += 100;
Console.WriteLine("After debiting,balance is {0}", balance);
}
}
}
}
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。