欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

.net Lock(this),Lock(obj),Lock("string") console app demo,线程安全

程序员文章站 2022-08-03 11:27:27
class program { static object obj = new object(); static int balance =...
class program
{
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
{
thread.sleep(500);
balance += 100;
console.writeline("after crediting,balance is {0}", balance);
}
}
}


private static void debit()
{
lock (obj)
{
for (int i = 0; i
{
thread.sleep(500);
balance -= 100;
console.writeline("after debiting,balance is {0}", balance);
}
}
}




static void creditnolock()
{
for (int i = 0; i
{
thread.sleep(1000);
balance += 100;
console.writeline("after crediting,balance is {0}", balance);
}
}


private static void debitnolock()
{
for (int i = 0; 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
{
thread.sleep(1000);
balance -= 100;
console.writeline("after debiting,balance is {0}", balance);
}
}
}


public void debit()
{
lock (this)
{
for (int i = 0; i
{
thread.sleep(1000);
balance += 100;
console.writeline("after debiting,balance is {0}", balance);
}
}
}




public void creditlockobj()
{
lock (obj)
{
for (int i = 0; i
{


thread.sleep(1000);
balance -= 100;
console.writeline("after debiting,balance is {0}", balance);
}
}
}


public void debitlockobj()
{
lock (obj)
{
for (int i = 0; i
{
thread.sleep(1000);
balance += 100;
console.writeline("after debiting,balance is {0}", balance);
}
}
}

}