当前位置: 移动技术网 > IT编程>开发语言>.net > .net Lock(this),Lock(obj),Lock("string") console app demo,线程安全

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

2019年05月10日  | 移动技术网IT编程  | 我要评论

拾芝麻凑斗,好听 的歌,创业加盟论坛

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 < 15;="">
{
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;="">
{
thread.sleep(500);
balance -= 100;
console.writeline("after debiting,balance is {0}", balance);
}
}
}




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


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


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




public void creditlockobj()
{
lock (obj)
{
for (int i = 0; i < 5;="">
{


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


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

}



如对本文有疑问,请在下面进行留言讨论,广大热心网友会与你互动!! 点击进行留言回复

相关文章:

验证码:
移动技术网