您好,登錄后才能下訂單哦!
可重入鎖:鎖可以連續(xù)使用
計(jì)數(shù)器+判斷進(jìn)入的線程是不是已經(jīng)鎖定的線程,如果是那就不用等待,直接使用
public class my {
public static void main(String[]args)
{
my m=new my();
m.test();
}
public void test()
{
synchronized(this)//第一次獲得鎖
{
while(true)
{
synchronized(this)//第二次獲得鎖,假如沒(méi)有可重入鎖,將會(huì)造成死鎖
{
System.out.println("relock");
}
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
手工實(shí)現(xiàn):
public class my {
Lock lock=new Lock();
public void a() throws InterruptedException
{
lock.lock();
System.out.println(lock.getCount());
b();
lock.unlock();
System.out.println(lock.getCount());
}
public void b() throws InterruptedException
{
lock.lock();
System.out.println(lock.getCount());
//..
lock.unlock();
System.out.println(lock.getCount());
}
public static void main(String[]args) throws InterruptedException
{
my m=new my();
m.a();
Thread.sleep(1000);
System.out.println(m.lock.getCount());
}
}
class Lock{
//是否占用
private boolean isLocked=false;
private Thread lockedBy=null;//存儲(chǔ)線程,如果是自身就不等了
private int count=0;
//使用鎖
public synchronized void lock() throws InterruptedException
{
Thread t=Thread.currentThread();
while(isLocked&&lockedBy!=t)//如果被鎖住了,且不是當(dāng)前線程
{
wait();
}
isLocked=true;
lockedBy=t;
count++;
}
//釋放鎖
public synchronized void unlock()
{
if(Thread.currentThread()==lockedBy)
{
count--;
if(count==0)
{
isLocked=false;
notify();
lockedBy=null;
}
}
isLocked=false;
notify();
}
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。