并发 -- Lock & Condition

一、概念

synchronized是Java语言的关键字,是内置特性,而ReentrantLock是一个实现了Lock接口的类,通过该类可以实现线程的同步。

synchronized和ReentrantLock都是可重入锁。当一个线程执行到某个synchronized方法时,比如method1,而在method1中会调用另外一个synchronized方法,比如method2,此时线程不必重新去申请锁,而是可以直接执行方法method2。

二、ReentrantLock

主要方法:
lock():获取不到锁就不罢休,否则线程一直处于阻塞状态。
tryLock():尝试性地获取锁,不管有没有获取到都马上返回,拿到锁就返回true,不然就返回false。
tryLock(long time, TimeUnit unit):如果获取不到锁,就等待一段时间,超时返回false。
lockInterruptibly():线程调用lockInterruptibly()方法获取锁,未获取到处于阻塞状态,此时如果调用该线程的interrupt()方法会唤醒该线程并要求处理InterruptedException。

static class MyThread extends Thread {
    private static Lock lock = new ReentrantLock();

    private MyThread(String name) {
        setName(name);
    }

    @Override
    public void run() {
        Log.d(TAG, "zwm, thread: " + getName() + " run start");
        try {
            lock.lockInterruptibly();
            Log.d(TAG, "zwm, thread: " + getName() + " acquire lock");
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
            Log.d(TAG, "zwm, thread: " + getName() + " InterruptedException");
        } finally {
            try {
                lock.unlock();
                Log.d(TAG, "zwm, thread: " + getName() + " release lock");
            } catch (IllegalMonitorStateException e) {
                e.printStackTrace();
                Log.d(TAG, "zwm, thread: " + getName() + " IllegalMonitorStateException");
            }
        }
        Log.d(TAG, "zwm, thread: " + getName() + " run end");
    }
}

//测试代码
MyThread thread1 = new MyThread("thread1");
thread1.start();
try {
    Thread.sleep(1000);
} catch (InterruptedException e) {
    e.printStackTrace();
}

MyThread thread2 = new MyThread("thread2");
thread2.start();
try {
    Thread.sleep(1000);
} catch (InterruptedException e) {
    e.printStackTrace();
}

thread2.interrupt();

//输出
02-11 21:22:13.046 zwm, thread: thread1 run start
02-11 21:22:13.046 zwm, thread: thread1 acquire lock
02-11 21:22:14.046 zwm, thread: thread2 run start
02-11 21:22:15.048 zwm, thread: thread2 InterruptedException
02-11 21:22:15.049 zwm, thread: thread2 IllegalMonitorStateException
02-11 21:22:15.049 zwm, thread: thread2 run end
02-11 21:22:23.047 zwm, thread: thread1 release lock
02-11 21:22:23.047 zwm, thread: thread1 run end

三、ReentrantReadWriteLock

可重入读写锁,实现了ReadWriteLock接口:

public interface ReadWriteLock {
    Lock readLock();
    Lock writeLock();
}

现实中有这样一种场景:对共享资源有读和写的操作,且写操作没有读操作那么频繁。在没有写操作的时候,多个线程同时读一个资源没有任何问题,所以应该允许多个线程同时读取共享资源;但是如果一个线程想去写这些共享资源,就不应该允许其他线程对该资源进行读和写的操作了。

针对这种场景,Java的并发包提供了读写锁ReentrantReadWriteLock,它表示两个锁,一个是读操作相关的锁,称为共享锁;一个是写相关的锁,称为排他锁。

线程进入读锁的前提条件:

  • 没有其他线程的写锁。
  • 没有写请求,或者有写请求但调用线程和持有锁的线程是同一个。

线程进入写锁的前提条件:

  • 没有其他线程的读锁。
  • 没有其他线程的写锁。

读写锁有以下三个重要的特性:

  • 公平选择性:支持非公平(默认)和公平的锁获取方式,吞吐量还是非公平优于公平。
  • 重进入:读锁和写锁都支持线程重进入。
  • 锁降级:遵循获取写锁、获取读锁、再释放写锁的次序,写锁能够降级成为读锁。

读锁:

static class MyThread extends Thread{
    private static ReentrantReadWriteLock.ReadLock lock = new ReentrantReadWriteLock().readLock();

    private MyThread(String name) {
        setName(name);
    }

    @Override
    public void run() {
        Log.d(TAG, "zwm, thread: " + getName() + " run start");
        lock.lock();
        Log.d(TAG, "zwm, thread: " + getName() + " acquire lock");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
            Log.d(TAG, "zwm, thread: " + getName() + " release lock");
        }
        Log.d(TAG, "zwm, thread: " + getName() + " run end");
    }
}

//测试代码 
MyThread thread1 = new MyThread("thread1");
thread1.start();
MyThread thread2 = new MyThread("thread2");
thread2.start();
MyThread thread3 = new MyThread("thread3");
thread3.start();

//输出
02-11 22:52:10.112 zwm, thread: thread1 run start
02-11 22:52:10.112 zwm, thread: thread1 acquire lock
02-11 22:52:10.113 zwm, thread: thread2 run start
02-11 22:52:10.113 zwm, thread: thread3 run start
02-11 22:52:10.113 zwm, thread: thread2 acquire lock
02-11 22:52:10.113 zwm, thread: thread3 acquire lock
02-11 22:52:12.113 zwm, thread: thread1 release lock
02-11 22:52:12.113 zwm, thread: thread1 run end
02-11 22:52:12.114 zwm, thread: thread3 release lock
02-11 22:52:12.114 zwm, thread: thread3 run end
02-11 22:52:12.114 zwm, thread: thread2 release lock
02-11 22:52:12.114 zwm, thread: thread2 run end

写锁:

static class MyThread extends Thread{
    private static ReentrantReadWriteLock.WriteLock lock = new ReentrantReadWriteLock().writeLock();

    private MyThread(String name) {
        setName(name);
    }

    @Override
    public void run() {
        Log.d(TAG, "zwm, thread: " + getName() + " run start");
        lock.lock();
        Log.d(TAG, "zwm, thread: " + getName() + " acquire lock");
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
            Log.d(TAG, "zwm, thread: " + getName() + " release lock");
        }
        Log.d(TAG, "zwm, thread: " + getName() + " run end");
    }
}

//测试代码
MyThread thread1 = new MyThread("thread1");
thread1.start();
MyThread thread2 = new MyThread("thread2");
thread2.start();
MyThread thread3 = new MyThread("thread3");
thread3.start();

//输出
02-11 22:55:44.916 zwm, thread: thread3 run start
02-11 22:55:44.917 zwm, thread: thread3 acquire lock
02-11 22:55:44.917 zwm, thread: thread2 run start
02-11 22:55:44.917 zwm, thread: thread1 run start
02-11 22:55:46.917 zwm, thread: thread2 acquire lock
02-11 22:55:46.917 zwm, thread: thread3 release lock
02-11 22:55:46.918 zwm, thread: thread3 run end
02-11 22:55:48.918 zwm, thread: thread1 acquire lock
02-11 22:55:48.918 zwm, thread: thread2 release lock
02-11 22:55:48.919 zwm, thread: thread2 run end
02-11 22:55:50.919 zwm, thread: thread1 release lock
02-11 22:55:50.919 zwm, thread: thread1 run end

四、Lock与synchronized的比较

  • Lock是一个接口,而synchronized是Java中的关键字,synchronized是内置的语言实现。
  • synchronized在发生异常时,会自动释放线程占有的锁,因此不会导致死锁现象发生。Lock在发生异常时,如果没有主动通过unLock()方法去释放锁,则很可能造成死锁的现象,因此使用Lock时需要在finally块中释放锁。
  • Lock可以让等待锁的线程响应中断,而synchronized却不行,使用synchronized时,等待的线程会一直等待下去,不能够响应中断。
  • 通过Lock可以知道有没有成功获取锁,而synchronized却无法办到。
  • Lock可以提高多个线程进行读操作的效率。

五、Condition

Lock用于控制多线程对同一状态的顺序访问,保证该状态的连续性。
Condition用于控制多线程之间的基于该状态的条件等待。

生产者消费者简单模型:生产者往buffer里put,消费者从buffer里take。
1.同一状态的顺序访问
有三个状态需要顺序访问:buffer的大小count,生产者用于put的游标putptr,消费者用于take的游标takeptr。
2.基于该状态的条件等待
当count = 0时,消费者的take需要等待;当count = buffer.size时,生产者的put需要等待。

使用Lock & Condition实现生产者消费者简单模型:

class BoundedBuffer {
    final Lock lock = new ReentrantLock();
    final Condition notFull = lock.newCondition();
    final Condition notEmpty = lock.newCondition();
    final Object[] items = new Object[5];
    int putptr, takeptr, count;

    public void put(Object x) throws InterruptedException {
        lock.lock();
        Log.d(TAG, "zwm, put method, thread: " + Thread.currentThread().getName() + " acquire lock");
        try {
            while (count == items.length) {
                Log.d(TAG, "zwm, buffer full, thread: " + Thread.currentThread().getName() + " await using notFull condition");
                notFull.await();
            }
            items[putptr] = x;
            Log.d(TAG, "zwm, thread: " + Thread.currentThread().getName() + " putptr: " + putptr + ", value: " + items[putptr]);
            if (++putptr == items.length) putptr = 0;
            ++count;
            Log.d(TAG, "zwm, put done, thread: " + Thread.currentThread().getName() + " signal other thread using notEmpty condition");
            notEmpty.signal();
        } finally {
            lock.unlock();
            Log.d(TAG, "zwm, put method, thread: " + Thread.currentThread().getName() + " release lock");
        }
    }

    public Object take() throws InterruptedException {
        lock.lock();
        Log.d(TAG, "zwm, take method, thread: " + Thread.currentThread().getName() + " acquire lock");
        try {
            while (count == 0) {
                Log.d(TAG, "zwm, buffer empty, thread: " + Thread.currentThread().getName() + " await using notEmpty condition");
                notEmpty.await();
            }
            Object x = items[takeptr];
            Log.d(TAG, "zwm, thread: " + Thread.currentThread().getName() + " takeptr: " + takeptr + ", value: " + items[takeptr]);
            if (++takeptr == items.length) takeptr = 0;
            --count;
            Log.d(TAG, "zwm, take done, thread: " + Thread.currentThread().getName() + " signal other thread using notFull condition");
            notFull.signal();
            return x;
        } finally {
            lock.unlock();
            Log.d(TAG, "zwm, take method, thread: " + Thread.currentThread().getName() + " release lock");
        }
    }
}

class PutThread extends Thread {
    private BoundedBuffer buffer;

    public PutThread(String name, BoundedBuffer buffer) {
        setName(name);
        this.buffer = buffer;
    }

    @Override
    public void run() {
        for(int i=0; i<5; i++) {
            try {
                buffer.put(String.valueOf(i));
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

class TakeThread extends Thread {
    private BoundedBuffer buffer;

    public TakeThread(String name, BoundedBuffer buffer) {
        setName(name);
        this.buffer = buffer;
    }

    @Override
    public void run() {
        for(int i=0; i<5; i++) {
            try {
                buffer.take();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
    }
}

//测试代码
BoundedBuffer buffer = new BoundedBuffer();
PutThread putThread1 = new PutThread("putThread1", buffer);
putThread1.start();
TakeThread takeThread1 = new TakeThread("takeThread1", buffer);
takeThread1.start();
TakeThread takeThread2 = new TakeThread("takeThread2", buffer);
takeThread2.start();

//输出
2019-02-12 14:27:44.717 zwm, put method, thread: putThread1 acquire lock
2019-02-12 14:27:44.717 zwm, thread: putThread1 putptr: 0, value: 0
2019-02-12 14:27:44.717 zwm, put done, thread: putThread1 signal other thread using notEmpty condition
2019-02-12 14:27:44.717 zwm, put method, thread: putThread1 release lock
2019-02-12 14:27:44.718 zwm, take method, thread: takeThread1 acquire lock
2019-02-12 14:27:44.719 zwm, thread: takeThread1 takeptr: 0, value: 0
2019-02-12 14:27:44.719 zwm, take done, thread: takeThread1 signal other thread using notFull condition
2019-02-12 14:27:44.719 zwm, take method, thread: takeThread1 release lock
2019-02-12 14:27:44.719 zwm, take method, thread: takeThread2 acquire lock
2019-02-12 14:27:44.719 zwm, buffer empty, thread: takeThread2 await using notEmpty condition //buffer空,takeThread2等待,释放锁
2019-02-12 14:27:44.720 zwm, take method, thread: takeThread1 acquire lock //takeThread1获取锁
2019-02-12 14:27:44.721 zwm, buffer empty, thread: takeThread1 await using notEmpty condition //buffer空,takeThread1等待,释放锁
2019-02-12 14:27:45.718 zwm, put method, thread: putThread1 acquire lock
2019-02-12 14:27:45.718 zwm, thread: putThread1 putptr: 1, value: 1
2019-02-12 14:27:45.718 zwm, put done, thread: putThread1 signal other thread using notEmpty condition
2019-02-12 14:27:45.718 zwm, put method, thread: putThread1 release lock
2019-02-12 14:27:45.718 zwm, thread: takeThread2 takeptr: 1, value: 1 //takeThread2被唤醒,获取锁
2019-02-12 14:27:45.718 zwm, take done, thread: takeThread2 signal other thread using notFull condition
2019-02-12 14:27:45.719 zwm, take method, thread: takeThread2 release lock
2019-02-12 14:27:45.719 zwm, take method, thread: takeThread2 acquire lock //takeThread2获取锁
2019-02-12 14:27:45.719 zwm, buffer empty, thread: takeThread2 await using notEmpty condition //buffer空,takeThread2等待,释放锁
2019-02-12 14:27:46.719 zwm, put method, thread: putThread1 acquire lock
2019-02-12 14:27:46.719 zwm, thread: putThread1 putptr: 2, value: 2
2019-02-12 14:27:46.720 zwm, put done, thread: putThread1 signal other thread using notEmpty condition
2019-02-12 14:27:46.720 zwm, put method, thread: putThread1 release lock
2019-02-12 14:27:46.721 zwm, thread: takeThread1 takeptr: 2, value: 2 //takeThread1被唤醒,获取锁
2019-02-12 14:27:46.721 zwm, take done, thread: takeThread1 signal other thread using notFull condition
2019-02-12 14:27:46.721 zwm, take method, thread: takeThread1 release lock
2019-02-12 14:27:46.722 zwm, take method, thread: takeThread1 acquire lock //takeThread1获取锁
2019-02-12 14:27:46.722 zwm, buffer empty, thread: takeThread1 await using notEmpty condition //buffer空,takeThread1等待,释放锁
2019-02-12 14:27:47.721 zwm, put method, thread: putThread1 acquire lock
2019-02-12 14:27:47.721 zwm, thread: putThread1 putptr: 3, value: 3
2019-02-12 14:27:47.721 zwm, put done, thread: putThread1 signal other thread using notEmpty condition
2019-02-12 14:27:47.721 zwm, put method, thread: putThread1 release lock
2019-02-12 14:27:47.722 zwm, thread: takeThread2 takeptr: 3, value: 3
2019-02-12 14:27:47.722 zwm, take done, thread: takeThread2 signal other thread using notFull condition
2019-02-12 14:27:47.722 zwm, take method, thread: takeThread2 release lock
2019-02-12 14:27:47.722 zwm, take method, thread: takeThread2 acquire lock
2019-02-12 14:27:47.722 zwm, buffer empty, thread: takeThread2 await using notEmpty condition //buffer空,takeThread2等待,释放锁
2019-02-12 14:27:48.722 zwm, put method, thread: putThread1 acquire lock
2019-02-12 14:27:48.722 zwm, thread: putThread1 putptr: 4, value: 4
2019-02-12 14:27:48.722 zwm, put done, thread: putThread1 signal other thread using notEmpty condition
2019-02-12 14:27:48.723 zwm, put method, thread: putThread1 release lock
2019-02-12 14:27:48.723 zwm, thread: takeThread1 takeptr: 4, value: 4
2019-02-12 14:27:48.723 zwm, take done, thread: takeThread1 signal other thread using notFull condition
2019-02-12 14:27:48.724 zwm, take method, thread: takeThread1 release lock
2019-02-12 14:27:48.724 zwm, take method, thread: takeThread1 acquire lock
2019-02-12 14:27:48.724 zwm, buffer empty, thread: takeThread1 await using notEmpty condition //buffer空,takeThread1等待,释放锁
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 200,841评论 5 472
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 84,415评论 2 377
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 147,904评论 0 333
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 54,051评论 1 272
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 63,055评论 5 363
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 48,255评论 1 278
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 37,729评论 3 393
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 36,377评论 0 255
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 40,517评论 1 294
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 35,420评论 2 317
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 37,467评论 1 329
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 33,144评论 3 317
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 38,735评论 3 303
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 29,812评论 0 19
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 31,029评论 1 256
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 42,528评论 2 346
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 42,126评论 2 341

推荐阅读更多精彩内容