using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Threading;文章來(lái)源:http://www.zghlxwxcb.cn/news/detail-534200.html
namespace LockTest
{
class Program
{
static void Main(string[] args)
{
TestLock testlock = new TestLock();
Thread th = new Thread(() =>
{
//模擬死鎖:造成死鎖,使lock無(wú)法釋放,在i=5時(shí),跳出死循環(huán),釋放lock
testlock.DoWorkWithLock();
});
th.Start();
Thread.Sleep(1000);
Thread th2 = new Thread(() =>
{
//這個(gè)地方你可能會(huì)有疑惑,但存在這種情況,比如你封裝的dll,對(duì)其它開(kāi)發(fā)人員不是可見(jiàn)的
//開(kāi)發(fā)人員很有可能在他的邏輯中,加上一個(gè)lock保證方法同時(shí)被一個(gè)線(xiàn)程調(diào)用,但這時(shí)有其它的線(xiàn)程正在調(diào)用該方法,
//但并沒(méi)有釋放,死鎖了,那么在這里就不會(huì)被執(zhí)行,除非上面的線(xiàn)程釋放了lock鎖定的對(duì)象。這里的lock也可以理解為一個(gè)標(biāo)識(shí),線(xiàn)程1被鎖定的對(duì)象
//是否已經(jīng)被釋放,
//如果沒(méi)有釋放,則無(wú)法繼續(xù)訪(fǎng)問(wèn)lock塊中的代碼。
lock (testlock)
{
// 如果該對(duì)象中l(wèi)ock(this)不釋放(testlock與this指的是同一個(gè)對(duì)象),則其它線(xiàn)程如果調(diào)用該方法,則會(huì)出現(xiàn)直到lock(this)釋放后才能繼續(xù)調(diào)用。
testlock.MotherCallYouDinner();
testlock.DoWorkWithLock();
}
});
th2.Start();
Console.Read();
}
}文章來(lái)源地址http://www.zghlxwxcb.cn/news/detail-534200.html
class TestLock
{
public static readonly object objLock = new object();
/// <summary>
/// 該方法,希望某人在工作的時(shí)候,其它人不要打擾(希望只有一個(gè)線(xiàn)程在執(zhí)行)
/// </summary>
/// <param name="methodIndex"></param>
public void DoWorkWithLock()
{
//鎖當(dāng)前對(duì)象
lock (this)
{
Console.WriteLine("lock this");
int i = 0;
while (true)
{
Console.WriteLine("At work, do not disturb...,Thread id is " + Thread.CurrentThread.ManagedThreadId.ToString());
Thread.Sleep(1000);
if (i == 5)
{
break;
}
Console.WriteLine(i.ToString());
i++;
}
}
Console.WriteLine("lock dispose");
}
public void MotherCallYouDinner()
{
Console.WriteLine("Your mother call you to home for dinner.");
}
}
}
到了這里,關(guān)于C#加鎖的例程的文章就介紹完了。如果您還想了解更多內(nèi)容,請(qǐng)?jiān)谟疑辖撬阉鱐OY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!