java 中Lock的使用【轉(zhuǎn)】

ReentrantLock也能夠讓代碼塊原子執(zhí)行,但是比synchronized更加強(qiáng)大,ReentrantLock具有嗅探鎖定琼蚯、多路分支通知等功能僵蛛。
嗅探鎖定:是指獲取鎖時(shí)如果鎖已經(jīng)被其他線程獲取到ReentrantLock可以進(jìn)行指定等待時(shí)間獲取鎖或者
多路分支通知:是指線程發(fā)生await時(shí),線程可以選擇注冊(cè)在不同的監(jiān)視器Condition對(duì)象上瑟幕,在適當(dāng)?shù)臅r(shí)候可以選擇指定的監(jiān)視器Condition對(duì)象上的線程進(jìn)行signal通知磕蒲、執(zhí)行
1、多線程執(zhí)行同一代碼塊互斥

import java.util.concurrent.locks.ReentrantLock;

class MyService {

    private ReentrantLock lock = new ReentrantLock();

    public void method() {
        try {
            lock.lock();
            for (int i = 1; i <= 3; i++) {
                Thread.sleep(1000);
                System.out.println("ThreadName=" + Thread.currentThread().getName() + "  " + i);
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }finally {
            lock.unlock();
        }
    }
}

class MyThread extends Thread {

    private MyService service;

    MyThread(MyService service) {
        this.service = service;
    }

    @Override
    public void run() {
        service.method();
    }
}

public class Test {

    public static void main(String[] args) {
        MyService service = new MyService();
        MyThread myThread1 = new MyThread(service);
        MyThread myThread2 = new MyThread(service);

        myThread1.start();
        myThread2.start();
    }
}

結(jié)果

ThreadName=Thread-0 1
ThreadName=Thread-0 2
ThreadName=Thread-0 3
ThreadName=Thread-1 1
ThreadName=Thread-1 2
ThreadName=Thread-1 3

2只盹、多線程執(zhí)行不同代碼塊互斥

import java.util.concurrent.locks.ReentrantLock;

class MyService {
    private ReentrantLock lock = new ReentrantLock();

    public void methodA() {
        lock.lock();
        try {
            System.out.println("MethodA begin ThreadName=" + Thread.currentThread().getName());
            for (int i = 1; i <= 3; i++) {
                System.out.println("ThreadName=" + Thread.currentThread().getName() + "  " + i);
                Thread.sleep(1000);
            }
            System.out.println("MethodA end ThreadName=" + Thread.currentThread().getName());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void methodB() {
        lock.lock();
        try {
            System.out.println("MethodB begin ThreadName=" + Thread.currentThread().getName());
            for (int i = 1; i <= 3; i++) {
                System.out.println("ThreadName=" + Thread.currentThread().getName() + "  " + i);
                Thread.sleep(1000);
            }
            System.out.println("MethodB end ThreadName=" + Thread.currentThread().getName());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
}

class ThreadA extends Thread {

    private MyService service;

    ThreadA(MyService service) {
        this.service = service;
    }

    @Override
    public void run() {
        service.methodA();
    }
}

class ThreadB extends Thread {

    private MyService service;

    ThreadB(MyService service) {
        this.service = service;
    }

    @Override
    public void run() {
        service.methodB();
    }
}

public class Test {

    public static void main(String[] args) {
        MyService service = new MyService();
        ThreadA threadA = new ThreadA(service);
        threadA.setName("A");

        ThreadB threadB = new ThreadB(service);
        threadB.setName("B");
        threadA.start();
        threadB.start();
    }
}

結(jié)果:

MethodA begin ThreadName=A
ThreadName=A 1
ThreadName=A 2
ThreadName=A 3
MethodA end ThreadName=A
MethodB begin ThreadName=B
ThreadName=B 1
ThreadName=B 2
ThreadName=B 3
MethodB end ThreadName=B

3辣往、多路通知

當(dāng)多線程進(jìn)入await狀態(tài)時(shí),利用Condition監(jiān)視器對(duì)不同類型線程通知

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

class MyService {
    private ReentrantLock lock = new ReentrantLock();
    private Condition conditionA = lock.newCondition();
    private Condition conditionB = lock.newCondition();

    public void methodA() {
        lock.lock();
        try {
            System.out.println("MethodA begin ThreadName=" + Thread.currentThread().getName() + "  " + System.currentTimeMillis());
            conditionA.await();
            System.out.println("MethodA end ThreadName=" + Thread.currentThread().getName() + "  " + System.currentTimeMillis());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void methodB() {
        lock.lock();
        try {
            System.out.println("MethodB begin ThreadName=" + Thread.currentThread().getName() + "  " + System.currentTimeMillis());
            conditionB.await();
            System.out.println("MethodB end ThreadName=" + Thread.currentThread().getName() + "  " + System.currentTimeMillis());
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    public void signalA() {
        lock.lock();
        conditionA.signal();
        lock.unlock();
    }
    public void signalA_All() {
        lock.lock();
        conditionA.signalAll();
        lock.unlock();
    }


    public void signalB() {
        lock.lock();
        conditionB.signal();
        lock.unlock();
    }
    public void signalB_All() {
        lock.lock();
        conditionB.signalAll();
        lock.unlock();
    }
}

class ThreadA extends Thread {

    private MyService service;

    ThreadA(MyService service) {
        this.service = service;
    }

    @Override
    public void run() {
        service.methodA();
    }
}

class ThreadB extends Thread {

    private MyService service;

    ThreadB(MyService service) {
        this.service = service;
    }

    @Override
    public void run() {
        service.methodB();
    }
}

public class Test {

    public static void main(String[] args) throws InterruptedException {
        MyService service = new MyService();
        ThreadA threadA = new ThreadA(service);
        threadA.setName("A");

        ThreadB threadB = new ThreadB(service);
        threadB.setName("B");
        threadA.start();
        threadB.start();

        Thread.sleep(1000);
        service.signalA();
        Thread.sleep(1000);
        service.signalB();

//        ThreadA[] threadAs = new ThreadA[10];
//        for (int i=0;i<5;i++){
//            threadAs[i] = new ThreadA(service);
//        }
//        ThreadB[] threadBs = new ThreadB[10];
//        for (int i=0;i<5;i++){
//            threadBs[i] = new ThreadB(service);
//        }
//
//        for (int i=0;i<5;i++){
//            threadAs[i].start();
//            threadBs[i].start();
//        }
//
//        Thread.sleep(1000);
//        service.signalA_All();
//        Thread.sleep(1000);
//        service.signalB_All();
    }
}

測(cè)試結(jié)果1:

MethodA begin ThreadName=A 1476800025028
MethodB begin ThreadName=B 1476800025029
MethodA end ThreadName=A 1476800026028
MethodB end ThreadName=B 1476800027028

修改代碼為:

 public static void main(String[] args) throws InterruptedException {
        MyService service = new MyService();
//        ThreadA threadA = new ThreadA(service);
//        threadA.setName("A");
//
//        ThreadB threadB = new ThreadB(service);
//        threadB.setName("B");
//        threadA.start();
//        threadB.start();
//
//        Thread.sleep(1000);
//        service.signalA();
//        Thread.sleep(1000);
//        service.signalB();

        ThreadA[] threadAs = new ThreadA[10];
        for (int i=0;i<5;i++){
            threadAs[i] = new ThreadA(service);
        }
        ThreadB[] threadBs = new ThreadB[10];
        for (int i=0;i<5;i++){
            threadBs[i] = new ThreadB(service);
        }

        for (int i=0;i<5;i++){
            threadAs[i].start();
            threadBs[i].start();
        }

        Thread.sleep(1000);
        service.signalA_All();
        Thread.sleep(1000);
        service.signalB_All();
    }

結(jié)果為:

MethodA begin ThreadName=Thread-0 1476800227416
MethodB begin ThreadName=Thread-7 1476800227417
MethodB begin ThreadName=Thread-5 1476800227417
MethodA begin ThreadName=Thread-3 1476800227418
MethodA begin ThreadName=Thread-1 1476800227418
MethodA begin ThreadName=Thread-4 1476800227418
MethodB begin ThreadName=Thread-6 1476800227418
MethodA begin ThreadName=Thread-2 1476800227418
MethodB begin ThreadName=Thread-8 1476800227418
MethodB begin ThreadName=Thread-9 1476800227418
MethodA end ThreadName=Thread-0 1476800228419
MethodA end ThreadName=Thread-3 1476800228419
MethodA end ThreadName=Thread-1 1476800228419
MethodA end ThreadName=Thread-4 1476800228420
MethodA end ThreadName=Thread-2 1476800228420
MethodB end ThreadName=Thread-7 1476800229419
MethodB end ThreadName=Thread-5 1476800229419
MethodB end ThreadName=Thread-6 1476800229419
MethodB end ThreadName=Thread-8 1476800229419
MethodB end ThreadName=Thread-9 1476800229419

4殖卑、公平所與非公平鎖
公平鎖是指線程獲(getting)取鎖的順序和線程鎖定(got)的順序相同站削,

Lock的一些方法說明
A) getHoldCount()
獲取當(dāng)前鎖定(got)的個(gè)數(shù)
B)getQueueLength()
獲取當(dāng)前正在等待獲取(getting)鎖的線程數(shù)(Threads)
C)getWaitQueueLength(Condition)
返回等待(await)與此鎖定(got)的Condition相關(guān)的個(gè)數(shù)

原文:https://blog.csdn.net/jihaitaowangyi/article/details/52852693

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
  • 序言:七十年代末孵稽,一起剝皮案震驚了整個(gè)濱河市许起,隨后出現(xiàn)的幾起案子,更是在濱河造成了極大的恐慌肛冶,老刑警劉巖街氢,帶你破解...
    沈念sama閱讀 211,884評(píng)論 6 492
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場(chǎng)離奇詭異睦袖,居然都是意外死亡珊肃,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 90,347評(píng)論 3 385
  • 文/潘曉璐 我一進(jìn)店門馅笙,熙熙樓的掌柜王于貴愁眉苦臉地迎上來伦乔,“玉大人,你說我怎么就攤上這事董习×液停” “怎么了?”我有些...
    開封第一講書人閱讀 157,435評(píng)論 0 348
  • 文/不壞的土叔 我叫張陵皿淋,是天一觀的道長(zhǎng)招刹。 經(jīng)常有香客問我恬试,道長(zhǎng),這世上最難降的妖魔是什么疯暑? 我笑而不...
    開封第一講書人閱讀 56,509評(píng)論 1 284
  • 正文 為了忘掉前任训柴,我火速辦了婚禮,結(jié)果婚禮上妇拯,老公的妹妹穿的比我還像新娘幻馁。我一直安慰自己,他們只是感情好越锈,可當(dāng)我...
    茶點(diǎn)故事閱讀 65,611評(píng)論 6 386
  • 文/花漫 我一把揭開白布仗嗦。 她就那樣靜靜地躺著,像睡著了一般甘凭。 火紅的嫁衣襯著肌膚如雪稀拐。 梳的紋絲不亂的頭發(fā)上,一...
    開封第一講書人閱讀 49,837評(píng)論 1 290
  • 那天对蒲,我揣著相機(jī)與錄音钩蚊,去河邊找鬼。 笑死蹈矮,一個(gè)胖子當(dāng)著我的面吹牛砰逻,可吹牛的內(nèi)容都是我干的。 我是一名探鬼主播泛鸟,決...
    沈念sama閱讀 38,987評(píng)論 3 408
  • 文/蒼蘭香墨 我猛地睜開眼蝠咆,長(zhǎng)吁一口氣:“原來是場(chǎng)噩夢(mèng)啊……” “哼!你這毒婦竟也來了北滥?” 一聲冷哼從身側(cè)響起刚操,我...
    開封第一講書人閱讀 37,730評(píng)論 0 267
  • 序言:老撾萬榮一對(duì)情侶失蹤,失蹤者是張志新(化名)和其女友劉穎再芋,沒想到半個(gè)月后菊霜,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 44,194評(píng)論 1 303
  • 正文 獨(dú)居荒郊野嶺守林人離奇死亡济赎,尸身上長(zhǎng)有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點(diǎn)故事閱讀 36,525評(píng)論 2 327
  • 正文 我和宋清朗相戀三年鉴逞,在試婚紗的時(shí)候發(fā)現(xiàn)自己被綠了。 大學(xué)時(shí)的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片司训。...
    茶點(diǎn)故事閱讀 38,664評(píng)論 1 340
  • 序言:一個(gè)原本活蹦亂跳的男人離奇死亡构捡,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出壳猜,到底是詐尸還是另有隱情勾徽,我是刑警寧澤,帶...
    沈念sama閱讀 34,334評(píng)論 4 330
  • 正文 年R本政府宣布统扳,位于F島的核電站喘帚,受9級(jí)特大地震影響畅姊,放射性物質(zhì)發(fā)生泄漏。R本人自食惡果不足惜吹由,卻給世界環(huán)境...
    茶點(diǎn)故事閱讀 39,944評(píng)論 3 313
  • 文/蒙蒙 一涡匀、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧溉知,春花似錦、人聲如沸腕够。這莊子的主人今日做“春日...
    開封第一講書人閱讀 30,764評(píng)論 0 21
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽帚湘。三九已至玫荣,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間大诸,已是汗流浹背捅厂。 一陣腳步聲響...
    開封第一講書人閱讀 31,997評(píng)論 1 266
  • 我被黑心中介騙來泰國(guó)打工, 沒想到剛下飛機(jī)就差點(diǎn)兒被人妖公主榨干…… 1. 我叫王不留资柔,地道東北人焙贷。 一個(gè)月前我還...
    沈念sama閱讀 46,389評(píng)論 2 360
  • 正文 我出身青樓,卻偏偏與公主長(zhǎng)得像贿堰,于是被迫代替她去往敵國(guó)和親辙芍。 傳聞我的和親對(duì)象是個(gè)殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點(diǎn)故事閱讀 43,554評(píng)論 2 349

推薦閱讀更多精彩內(nèi)容