一、概念
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等待,释放锁