溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶(hù)服務(wù)條款》

java 多線程-可重入鎖

發(fā)布時(shí)間:2020-04-11 10:44:43 來(lái)源:網(wǎng)絡(luò) 閱讀:256 作者:wx5d21d5e6e5ab1 欄目:編程語(yǔ)言

可重入鎖:鎖可以連續(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;
}

}
向AI問(wèn)一下細(xì)節(jié)

免責(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)容。

AI