ReentrantLock类的使用。
ReentrantReadWriteLock类的使用。
在多线程中,可以使用synchronized来实现线程之间的同步互斥,在JDK1.5中新增了ReentrantLock类也可打到同样的效果,并在拓展功能上更强大,比如:嗅探锁定、多路分支通知等,使用上比synchronized更加灵活,下面我们在学习中来任务两者的异同吧!
public class MyService {
private Lock lock = new ReentrantLock();
public void testMethod() {
lock.lock();
for (int i = 0; i < 2; i++) {
System.out.println("ThreadName" + Thread.currentThread().getName() + " " + i);
}
lock.unlock();
}
}
lock()获取锁,unlock()释放锁。
public class MyThread extends Thread {
private MyService myService;
public MyThread(MyService myService) {
this.myService = myService;
}
@Override
public void run() {
myService.testMethod();
}
}
public class Run {
public static void main(String[] args) {
MyService myService = new MyService();
MyThread m1 = new MyThread(myService);
MyThread m2 = new MyThread(myService);
MyThread m3 = new MyThread(myService);
MyThread m4 = new MyThread(myService);
MyThread m5 = new MyThread(myService);
m1.start();
m2.start();
m3.start();
m4.start();
m5.start();
}
}
ThreadNameThread-1 0
ThreadNameThread-1 1
ThreadNameThread-0 0
ThreadNameThread-0 1
ThreadNameThread-3 0
ThreadNameThread-3 1
ThreadNameThread-4 0
ThreadNameThread-4 1
ThreadNameThread-2 0
ThreadNameThread-2 1
从打印结果来看,当一个线程调用unlock()方法释放锁后,其他线程抢到锁继续执行,下面我们继续做个试验:
public class MyService {
private Lock lock = new ReentrantLock();
public void methodA() {
try {
lock.lock();
System.out.println("methodA begin threadNAME=" + Thread.currentThread().getName() + " Time=" + System.currentTimeMillis());
Thread.sleep(2000);
System.out.println("methodA end threadNAME=" + Thread.currentThread().getName() + " Time=" + System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void methodB() {
try {
lock.lock();
System.out.println("methodB begin threadNAME=" + Thread.currentThread().getName() + " Time=" + System.currentTimeMillis());
Thread.sleep(2000);
System.out.println("methodB end threadNAME=" + Thread.currentThread().getName() + " Time=" + System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
public class ThreadA extends Thread {
private MyService myService;
public ThreadA(MyService myService) {
this.myService = myService;
}
@Override
public void run() {
myService.methodA();
}
}
public class ThreadAA extends Thread {
private MyService myService;
public ThreadAA(MyService myService) {
this.myService = myService;
}
@Override
public void run() {
myService.methodA();
}
}
public class ThreadB extends Thread {
private MyService myService;
public ThreadB(MyService myService) {
this.myService = myService;
}
@Override
public void run() {
myService.methodB();
}
}
public class ThreadBB extends Thread {
private MyService myService;
public ThreadBB(MyService myService) {
this.myService = myService;
}
@Override
public void run() {
myService.methodB();
}
}
public class Run {
public static void main(String[] args) throws InterruptedException {
MyService myService = new MyService();
ThreadA a = new ThreadA(myService);
a.setName("a");
a.start();
ThreadAA aa = new ThreadAA(myService);
aa.setName("aa");
aa.start();
Thread.sleep(100);
ThreadB b = new ThreadB(myService);
b.setName("b");
b.start();
ThreadBB bb = new ThreadBB(myService);
bb.setName("bb");
bb.start();
}
}
methodA begin threadNAME=a Time=1590990695499
methodA end threadNAME=a Time=1590990697502
methodA begin threadNAME=aa Time=1590990697502
methodA end threadNAME=aa Time=1590990699506
methodB begin threadNAME=bb Time=1590990699506
methodB end threadNAME=bb Time=1590990701507
methodB begin threadNAME=b Time=1590990701507
methodB end threadNAME=b Time=1590990703509
验证结果:调用lock()代码的线程就持有了对象监视器
,其他线程只有等待持有锁的线程释放。
synchronized与wait(),notify()或notifyAll()方法相结合,可以实现等待/通知模式。(对wait(),notify()或notifyAll()需要了解的可以看看一文详解wait与notify)
ReentrantLock
也可以实现同样的功能,但需要借助与Condition
对象。Condition
是JDK5中出现的,它有更好的灵活性,比如实现多路通知功能,也就是在一个Lock对象里面可以创建多个Condition
(即对象监视器)实例,线程对象可以注册在指定的Condition
中,从而有选择的进行通知,在调度线程上更加灵活。
使用nodify()
/notifyAll()
方法进行通知时,被通知的线程是JVM随机选择的。ReentrantLock
结合Condition
类是可以实现选择性通知。
synchronize就相当于整个Lock对象中只有一个单一的Condition对象,所有线程都注册在它一个对象的身上,notifyAll()时,需要通知所有的等待该对象的线程,JVM随机唤醒其中一个。
调用Condition.await方法前,如果没有持有合适的锁,则会报java.lang.IllegalMonitorStateException
的异常,我们可以通过ReentrantLock.lock()来获取锁。
下面我们使用Condition来实现一个等待通知模式:
public class MyService {
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
public void await() {
try {
lock.lock();
System.out.println("await start 时间为:" + System.currentTimeMillis());
condition.await();
System.out.println("await end 时间为:" + System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
lock.unlock();
}
}
public void signal(){
try {
lock.lock();
System.out.println("signal时间为:"+System.currentTimeMillis());
condition.signal();
}finally {
lock.unlock();
}
}
}
public class MyThread extends Thread {
private MyService myService;
public MyThread(MyService myService) {
this.myService = myService;
}
@Override
public void run() {
myService.await();
}
}
public class Run {
public static void main(String[] args) throws InterruptedException {
MyService myService = new MyService();
MyThread myThread = new MyThread(myService);
myThread.start();
Thread.sleep(3000);
myService.signal();
}
}
await start 时间为:1590995422964
signal时间为:1590995425971
await end 时间为:1590995425971
1)Object中的
wait()
方法相当于Condition类中的await()
。
2)Object中的wait(long timeout)
相当于Condition中的await(long time,TimeUnit unit)
。
3)Object中的notify()
相当于Condition中的signal()
。
4)Object中的notifyAll()
相当于Condition中的signalAll()
。
如何使用单个Condition来通知所有线程呢?
public class MyService {
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
public void awaitA() {
try {
lock.lock();
System.out.println("begin awaitA time = " + System.currentTimeMillis() + " thread Name = " + Thread.currentThread().getName());
condition.await();
System.out.println(" end awaitA time = " + System.currentTimeMillis() + " thread Name = " + Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void awaitB() {
try {
lock.lock();
System.out.println("begin awaitB time = " + System.currentTimeMillis() + " thread Name = " + Thread.currentThread().getName());
condition.await();
System.out.println(" end awaitB time = " + System.currentTimeMillis() + " thread Name = " + Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void signalAll() {
try {
lock.lock();
System.out.println(" signalAll time = " + System.currentTimeMillis() + " thread Name = " + Thread.currentThread().getName());
condition.signalAll();
} finally {
lock.unlock();
}
}
}
public class ThreadA extends Thread {
private MyService myService;
public ThreadA(MyService myService) {
this.myService = myService;
}
@Override
public void run() {
myService.awaitA();
}
}
public class ThreadB extends Thread {
private MyService myService;
public ThreadB(MyService myService) {
this.myService = myService;
}
@Override
public void run() {
myService.awaitB();
}
}
public class Run {
public static void main(String[] args) throws InterruptedException {
MyService myService = new MyService();
ThreadA a = new ThreadA(myService);
a.setName("a");
a.start();
ThreadB b = new ThreadB(myService);
b.setName("b");
b.start();
Thread.sleep(2000);
myService.signalAll();
}
}
begin awaitB time = 1590998606632 thread Name = b
begin awaitA time = 1590998606632 thread Name = a
signalAll time = 1590998608626 thread Name = main
end awaitB time = 1590998608626 thread Name = b
end awaitA time = 1590998608626 thread Name = a
那么如何使用多个Condition通知部分线程呢?
public class MyService {
private Lock lock = new ReentrantLock();
private Condition conditionA = lock.newCondition();
private Condition conditionB = lock.newCondition();
public void awaitA() {
try {
lock.lock();
System.out.println("begin awaitA time = " + System.currentTimeMillis() + " thread Name = " + Thread.currentThread().getName());
conditionA.await();
System.out.println(" end awaitA time = " + System.currentTimeMillis() + " thread Name = " + Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void awaitB() {
try {
lock.lock();
System.out.println("begin awaitB time = " + System.currentTimeMillis() + " thread Name = " + Thread.currentThread().getName());
conditionB.await();
System.out.println(" end awaitB time = " + System.currentTimeMillis() + " thread Name = " + Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void signalAllA() {
try {
lock.lock();
System.out.println(" signalAllA time = " + System.currentTimeMillis() + " thread Name = " + Thread.currentThread().getName());
conditionA.signalAll();
} finally {
lock.unlock();
}
}
public void signalAllB() {
try {
lock.lock();
System.out.println(" signalAllB time = " + System.currentTimeMillis() + " thread Name = " + Thread.currentThread().getName());
conditionA.signalAll();
} finally {
lock.unlock();
}
}
}
public class ThreadA extends Thread {
private MyService myService;
public ThreadA(MyService myService) {
this.myService = myService;
}
@Override
public void run() {
myService.awaitA();
}
}
public class ThreadB extends Thread {
private MyService myService;
public ThreadB(MyService myService) {
this.myService = myService;
}
@Override
public void run() {
myService.awaitB();
}
}
public class Run {
public static void main(String[] args) throws InterruptedException {
MyService myService = new MyService();
ThreadA a = new ThreadA(myService);
a.setName("a");
a.start();
ThreadB b = new ThreadB(myService);
b.setName("b");
b.start();
Thread.sleep(1000);
myService.signalAllA();
Thread.sleep(1000);
myService.signalAllB();
}
}
begin awaitB time = 1590999063461 thread Name = b
begin awaitA time = 1590999063485 thread Name = a
signalAllA time = 1590999064453 thread Name = main
end awaitA time = 1590999064453 thread Name = a
signalAllB time = 1590999065453 thread Name = main
单生产者与单消费者代码示例:
public class MyService {
private ReentrantLock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
private boolean hasValue = false;
public void set() {
try {
lock.lock();
while (hasValue == true) {
condition.await();
}
System.out.println("打印★");
hasValue = true;
condition.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void get() {
try {
lock.lock();
while (hasValue == false) {
condition.await();
}
System.out.println("打印☆");
hasValue = false;
condition.signal();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
public class ThreadA extends Thread {
private MyService myService;
public ThreadA(MyService myService) {
this.myService = myService;
}
@Override
public void run() {
for (int i = 0; i < Integer.MAX_VALUE; i++) {
myService.set();
}
}
}
public class ThreadB extends Thread {
private MyService myService;
public ThreadB(MyService myService) {
this.myService = myService;
}
@Override
public void run() {
for (int i = 0; i < Integer.MAX_VALUE; i++) {
myService.get();
}
}
}
public class Run {
public static void main(String[] args) {
MyService myService = new MyService();
ThreadA a = new ThreadA(myService);
a.start();
ThreadB b = new ThreadB(myService);
b.start();
}
}
···
打印☆
打印★
打印☆
打印★
打印☆
打印★
···
那么多生产与多消费怎么控制呢 ?
public class MyService {
private ReentrantLock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
private boolean hasValue = false;
public void set() {
try {
lock.lock();
while (hasValue == true) {
System.out.println("有可能★★连续");
condition.await();
}
System.out.println("打印★");
hasValue = true;
condition.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void get() {
try {
lock.lock();
while (hasValue == false) {
System.out.println("有可能☆☆连续");
condition.await();
}
System.out.println("打印☆");
hasValue = false;
condition.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
public class ThreadA extends Thread {
private MyService myService;
public ThreadA(MyService myService) {
this.myService = myService;
}
@Override
public void run() {
for (int i = 0; i < Integer.MAX_VALUE; i++) {
myService.set();
}
}
}
public class ThreadB extends Thread {
private MyService myService;
public ThreadB(MyService myService) {
this.myService = myService;
}
@Override
public void run() {
for (int i = 0; i < Integer.MAX_VALUE; i++) {
myService.get();
}
}
}
public class Run {
public static void main(String[] args) {
MyService myService = new MyService();
ThreadA[] a = new ThreadA[10];
ThreadB[] b = new ThreadB[10];
for (int i = 0; i < 10; i++) {
a[i] = new ThreadA(myService);
b[i] = new ThreadB(myService);
a[i].start();
b[i].start();
}
}
}
...
打印★
有可能★★连续
打印☆
打印★
有可能★★连续
有可能★★连续
有可能★★连续
有可能★★连续
有可能★★连续
有可能★★连续
打印☆
有可能☆☆连续
...
Lock
分为公平锁和非公平锁。
公平锁
:线程获取锁的顺序是按照线程加锁的顺序来分配的,即FIFO(先进先出)。
非公平锁
:随机获得锁。
那么下面我们就用代码来了解两种锁的特性吧。
非公平锁示例:
public class Service {
private ReentrantLock lock;
public Service(boolean isFair) {
this.lock = new ReentrantLock(isFair);
}
public void serviceMethod(){
try {
lock.lock();
System.out.println("ThreadName="+Thread.currentThread().getName()+"获取锁");
}finally {
lock.unlock();
}
}
}
public class Run {
public static void main(String[] args) {
final Service service = new Service(false);
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("★线程" + Thread.currentThread().getName() + "开始执行");
service.serviceMethod();
}
};
Thread[] threads = new Thread[10];
for (int i = 0; i < 10; i++) {
threads[i] = new Thread(runnable);
}
for (int i = 0; i < threads.length; i++) {
threads[i].start();
}
}
}
★线程Thread-0开始执行
ThreadName=Thread-0获取锁
★线程Thread-2开始执行
★线程Thread-1开始执行
ThreadName=Thread-2获取锁
★线程Thread-4开始执行
ThreadName=Thread-4获取锁
★线程Thread-5开始执行
★线程Thread-8开始执行
ThreadName=Thread-5获取锁
★线程Thread-9开始执行
ThreadName=Thread-9获取锁
★线程Thread-3开始执行
ThreadName=Thread-3获取锁
ThreadName=Thread-1获取锁
ThreadName=Thread-8获取锁
★线程Thread-7开始执行
ThreadName=Thread-7获取锁
★线程Thread-6开始执行
ThreadName=Thread-6获取锁
非公平锁的运行结果基本上是乱序的,先启动的线程不代表先获得锁。
公平锁示例:
修改Run.java代码如下
public class Run {
public static void main(String[] args) {
final Service service = new Service(true);
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println("★线程" + Thread.currentThread().getName() + "开始执行");
service.serviceMethod();
}
};
Thread[] threads = new Thread[10];
for (int i = 0; i < 10; i++) {
threads[i] = new Thread(runnable);
}
for (int i = 0; i < threads.length; i++) {
threads[i].start();
}
}
}
★线程Thread-1开始执行
★线程Thread-2开始执行
ThreadName=Thread-1获取锁
★线程Thread-5开始执行
★线程Thread-6开始执行
ThreadName=Thread-2获取锁
ThreadName=Thread-5获取锁
★线程Thread-0开始执行
★线程Thread-4开始执行
ThreadName=Thread-6获取锁
★线程Thread-8开始执行
ThreadName=Thread-0获取锁
★线程Thread-9开始执行
ThreadName=Thread-4获取锁
ThreadName=Thread-8获取锁
ThreadName=Thread-9获取锁
★线程Thread-3开始执行
ThreadName=Thread-3获取锁
★线程Thread-7开始执行
ThreadName=Thread-7获取锁
观察执行结果可以发现,启动的顺序与获得锁的顺序一致。
getHoldCount()
查询当前线程保持锁定的个数,也就是获取当前线程调用lock()的次数。
示例代码:
public class Service {
private ReentrantLock lock = new ReentrantLock();
private void serviceMethod1() {
try {
lock.lock();
System.out.println("serviceMethod1 getHoldCount=" + lock.getHoldCount());
serviceMethod2();
} finally {
lock.unlock();
}
}
private void serviceMethod2() {
try {
lock.lock();
System.out.println("serviceMethod2 getHoldCount=" + lock.getHoldCount());
} finally {
lock.unlock();
}
}
public static void main(String[] args) {
Service service = new Service();
service.serviceMethod1();
}
}
serviceMethod1 getHoldCount=1
serviceMethod2 getHoldCount=2
getQueueLength()
返回正等待获取此锁定的线程估计数。
代码示例:
public class Service {
private ReentrantLock lock = new ReentrantLock();
public void serviceMethod1() {
try {
lock.lock();
System.out.println("ThreadName=" + Thread.currentThread().getName());
Thread.sleep(10000);
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public static void main(String[] args) throws InterruptedException {
final Service service = new Service();
Runnable runnable = new Runnable() {
@Override
public void run() {
service.serviceMethod1();
}
};
Thread[] threads = new Thread[10];
for (int i = 0; i < 10; i++) {
threads[i] = new Thread(runnable);
}
for (int i = 0; i < 10; i++) {
threads[i].start();
}
Thread.sleep(2000);
System.out.println("有" + service.lock.getQueueLength() + "个线程在等待获取锁!");
}
}
ThreadName=Thread-0
有9个线程在等待获取锁!
···
getWaitQueueLength(Condition condition)
返回等待与此锁定相关的给定条件的Condition的线程估计数。
代码示例:
public class Service {
private ReentrantLock lock = new ReentrantLock();
private Condition newCondition = lock.newCondition();
public void waitMethod() {
try {
lock.lock();
newCondition.await();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void notifyMethod() {
try {
lock.lock();
System.out.println("有" + lock.getWaitQueueLength(newCondition) + "个线程正在等待newCondition");
newCondition.signalAll();
} finally {
lock.unlock();
}
}
public static void main(String[] args) throws InterruptedException {
final Service service = new Service();
Runnable runnable = new Runnable() {
@Override
public void run() {
service.waitMethod();
}
};
Thread[] threads = new Thread[10];
for (int i = 0; i < 10; i++) {
threads[i] = new Thread(runnable);
}
for (int i = 0; i < 10; i++) {
threads[i].start();
}
Thread.sleep(2000);
service.notifyMethod();
}
}
有10个线程正在等待newCondition
boolean hasQueuedThread(Thread thread)
查询指定线程是否正在等待获取此锁定。
boolean hasQueuedThreads()
查询是否有线程正在等待获取此锁定。
代码示例:
public class Service {
private ReentrantLock lock = new ReentrantLock();
public void waitMethod() {
try {
lock.lock();
System.out.println("threadName="+ Thread.currentThread().getName());
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public static void main(String[] args) throws InterruptedException {
final Service service = new Service();
Runnable runnable = new Runnable() {
@Override
public void run() {
service.waitMethod();
}
};
Thread threadA = new Thread(runnable);
threadA.start();
Thread.sleep(500);
Thread threadB = new Thread(runnable);
threadB.start();
Thread.sleep(500);
System.out.println(service.lock.hasQueuedThread(threadA));
System.out.println(service.lock.hasQueuedThread(threadB));
System.out.println(service.lock.hasQueuedThreads());
}
}
threadName=Thread-0
false
true
true
threadName=Thread-1
查询是否有线程正在等候与此锁定有关的condition条件。
代码示例:
public class Service {
private ReentrantLock lock = new ReentrantLock();
private Condition newCondition = lock.newCondition();
public void waitMethod() {
try {
lock.lock();
newCondition.await();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void notifyMethod() {
try {
lock.lock();
if (lock.hasWaiters(newCondition)) {
System.out.println("存在正在等待newCondition的线程,线程数:" + lock.getWaitQueueLength(newCondition));
newCondition.signalAll();
}
} finally {
lock.unlock();
}
}
public static void main(String[] args) throws InterruptedException {
final Service service = new Service();
Runnable runnable = new Runnable() {
@Override
public void run() {
service.waitMethod();
}
};
Thread[] threads = new Thread[10];
for (int i = 0; i < 10; i++) {
threads[i] = new Thread(runnable);
}
for (int i = 0; i < 10; i++) {
threads[i].start();
}
Thread.sleep(2000);
service.notifyMethod();
}
}
存在正在等待newCondition的线程,线程数:10
判断是否是公平锁。
/**
* Creates an instance of {@code ReentrantLock} with the
* given fairness policy.
*
* @param fair {@code true} if this lock should use a fair ordering policy
*/
public ReentrantLock(boolean fair) {
sync = fair ? new FairSync() : new NonfairSync();
}
/**
* Returns {@code true} if this lock has fairness set true.
*
* @return {@code true} if this lock has fairness set true
*/
public final boolean isFair() {
return sync instanceof FairSync;
}
查询当前线程是否持有该锁。
public class Service {
private ReentrantLock lock ;
public Service(boolean isFair) {
lock = new ReentrantLock(isFair);
}
public void serviceMethod(){
try {
System.out.println(lock.isHeldByCurrentThread());
lock.lock();
System.out.println(lock.isHeldByCurrentThread());
}finally {
lock.unlock();
}
}
public static void main(String[] args) {
final Service service = new Service(true);
new Runnable() {
@Override
public void run() {
service.serviceMethod();
}
}.run();
}
}
false
true
查询锁定是否由任意线程持有。
public class Service {
private ReentrantLock lock ;
public Service(boolean isFair) {
lock = new ReentrantLock(isFair);
}
public void serviceMethod(){
try {
System.out.println(lock.isLocked());
lock.lock();
System.out.println(lock.isLocked());
}finally {
lock.unlock();
}
}
public static void main(String[] args) {
final Service service = new Service(true);
new Runnable() {
@Override
public void run() {
service.serviceMethod();
}
}.run();
}
}
false
true
如果当前线程未被中断,则获取锁定,如果已经被中断则出现异常。
public class Service {
private ReentrantLock lock = new ReentrantLock();
public void serviceMethod() {
try {
lock.lockInterruptibly();
System.out.println("lock begin " + Thread.currentThread().getName());
for (int i = 0; i < Integer.MAX_VALUE / 10; i++) {
}
System.out.println("lock end " + Thread.currentThread().getName());
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
}
public static void main(String[] args) throws InterruptedException {
final Service service = new Service();
Runnable runnable = new Runnable() {
@Override
public void run() {
service.serviceMethod();
}
};
new Thread(runnable).start();
Thread.sleep(500);
Thread threadB = new Thread(runnable);
threadB.start();
threadB.interrupt();
}
}
lock begin Thread-0
lock end Thread-0
java.lang.InterruptedException
at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireInterruptibly(AbstractQueuedSynchronizer.java:1220)
at java.util.concurrent.locks.ReentrantLock.lockInterruptibly(ReentrantLock.java:335)
调用时锁定未被另一个线程持有的情况下,才获取该锁定。
public class Service {
private ReentrantLock lock = new ReentrantLock();
public void getLock() {
if (lock.tryLock()) {
System.out.println(Thread.currentThread().getName() + " 获得锁");
} else {
System.out.println(Thread.currentThread().getName() + " 未获得锁");
}
}
public static void main(String[] args) {
final Service service = new Service();
Runnable runnable = new Runnable(){
@Override
public void run() {
service.getLock();
}
};
Thread threadA = new Thread(runnable);
threadA.start();
Thread threadB = new Thread(runnable);
threadB.start();
}
}
Thread-0 获得锁
Thread-1 未获得锁
如果锁定在给定等待时间内没有被另一个线程持有,且当前线程未被终端,则获取该锁定。
public class Service {
private ReentrantLock lock = new ReentrantLock();
public void getLock() {
try {
if (lock.tryLock(3, TimeUnit.SECONDS)) {
System.out.println(Thread.currentThread().getName() + " 获得锁的时间:" + System.currentTimeMillis());
Thread.sleep(4000);
} else {
System.out.println(Thread.currentThread().getName() + " 未获得锁时间:" + System.currentTimeMillis());
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
}
public static void main(String[] args) {
final Service service = new Service();
Runnable runnable = new Runnable() {
@Override
public void run() {
System.out.println(Thread.currentThread().getName() + "调用时间:" + System.currentTimeMillis());
service.getLock();
}
};
Thread threadA = new Thread(runnable);
threadA.start();
Thread threadB = new Thread(runnable);
threadB.start();
}
}
Thread-0调用时间:1593673259015
Thread-0 获得锁的时间:1593673259016
Thread-1调用时间:1593673259015
Thread-1 未获得锁时间:1593673262017
public class Service {
private ReentrantLock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
public void testMethod() {
try {
lock.lock();
System.out.println("wait begin");
condition.await();
System.out.println("wait end");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
}
public static void main(String[] args) throws InterruptedException {
final Service service = new Service();
Runnable runnable = new Runnable() {
@Override
public void run() {
service.testMethod();
}
};
Thread thread = new Thread(runnable);
thread.start();
Thread.sleep(1000);
thread.interrupt();
}
}
wait begin
java.lang.InterruptedException
at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.reportInterruptAfterWait(AbstractQueuedSynchronizer.java:2014)
at java.util.concurrent.locks.AbstractQueuedSynchronizer$ConditionObject.await(AbstractQueuedSynchronizer.java:2048)
在sleep状态下,停止某一线程,会进入catch语句,并清除停止状态值,使之变成false。对于Thread基础不是很扎实的话,可以看看Thread基础回顾一下。
修改代码如下:
public class Service {
private ReentrantLock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
public void testMethod() {
try {
lock.lock();
System.out.println("wait begin");
condition.awaitUninterruptibly();
System.out.println("wait end");
} catch (Exception e) {
e.printStackTrace();
} finally {
if (lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
}
public static void main(String[] args) throws InterruptedException {
final Service service = new Service();
Runnable runnable = new Runnable() {
@Override
public void run() {
service.testMethod();
}
};
Thread thread = new Thread(runnable);
thread.start();
Thread.sleep(1000);
thread.interrupt();
}
}
wait begin
对比结果:awaitUninterruptibly()
与await()
作用相同,但不会再等待过程中响应中断。
使用Condition对象可以对线程执行的业务进行排序规划。
代码如下:
public class Run {
volatile private static int nextPrintWho = 1;
private static ReentrantLock lock = new ReentrantLock();
private static Condition conditionA = lock.newCondition();
private static Condition conditionB = lock.newCondition();
private static Condition conditionC = lock.newCondition();
public static void main(String[] args) {
Thread threadA = new Thread(new Runnable() {
@Override
public void run() {
try {
lock.lock();
while (nextPrintWho != 1) {
conditionA.await();
}
System.out.println("threadA" + nextPrintWho);
nextPrintWho = 2;
conditionB.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
});
Thread threadB = new Thread(new Runnable() {
@Override
public void run() {
try {
lock.lock();
while (nextPrintWho != 2) {
conditionB.await();
}
System.out.println("threadB" + nextPrintWho);
nextPrintWho = 3;
conditionC.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
});
Thread threadC = new Thread(new Runnable() {
@Override
public void run() {
try {
lock.lock();
while (nextPrintWho != 3) {
conditionC.await();
}
System.out.println("threadC" + nextPrintWho);
nextPrintWho = 1;
conditionA.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
});
Thread[] threadsA = new Thread[5];
Thread[] threadsB = new Thread[5];
Thread[] threadsC = new Thread[5];
for (int i = 0; i < 5; i++) {
threadsA[i] = new Thread(threadA);
threadsB[i] = new Thread(threadB);
threadsC[i] = new Thread(threadC);
threadsA[i].start();
threadsB[i].start();
threadsC[i].start();
}
}
}
threadA1
threadB2
threadC3
threadA1
threadB2
threadC3
threadA1
threadB2
threadC3
threadA1
threadB2
threadC3
threadA1
threadB2
threadC3
ReentrantLock具有完全互斥排他的效果,即同一时间只有一个线程在执行ReentrantLock.lock()方法后面的任务。这样做虽然保证了实例变量的线程安全性,但效率却是非常低下的,所以在JDK中提供了一种读写锁ReentrantReadWriteLock类,在某些不需要操作实例变量的方法中,完全可以使用读写锁来提升代码运行速度。
读写锁表示也有两个锁,一个是读操作相关的锁,也称为共享锁
;另一个是写操作相关的锁,也叫排他锁
。也就是多个读锁之间不互斥,读锁与写锁互斥,写锁与写锁互斥。即多个线程可以同时进行读取操作,但是同一时刻只允许一个线程进行写操作。
public class Service {
private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
private void read() {
try {
lock.readLock().lock();
System.out.println(Thread.currentThread().getName() + " 获取到读锁 " + System.currentTimeMillis());
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.readLock().unlock();
}
}
public static void main(String[] args) {
final Service service = new Service();
Thread threadA = new Thread(new Runnable() {
@Override
public void run() {
service.read();
}
});
Thread threadB = new Thread(new Runnable() {
@Override
public void run() {
service.read();
}
});
threadA.start();
threadB.start();
}
}
Thread-1 获取到读锁 1593755228144
Thread-0 获取到读锁 1593755228144
public class Service {
private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
private void read() {
try {
lock.writeLock().lock();
System.out.println(Thread.currentThread().getName() + " 获取到写锁 " + System.currentTimeMillis());
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.writeLock().unlock();
}
}
public static void main(String[] args) {
final Service service = new Service();
Thread threadA = new Thread(new Runnable() {
@Override
public void run() {
service.read();
}
});
Thread threadB = new Thread(new Runnable() {
@Override
public void run() {
service.read();
}
});
threadA.start();
threadB.start();
}
}
Thread-0 获取到写锁 1593755364185
Thread-1 获取到读锁 1593755369185
writeLock()在同一时间只允许一个线程执行lock后面的方法。
public class Service {
private ReentrantReadWriteLock lock = new ReentrantReadWriteLock();
private void read() {
try {
lock.readLock().lock();
System.out.println(Thread.currentThread().getName() + " 获取到读锁 " + System.currentTimeMillis());
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.readLock().unlock();
}
}
private void write() {
try {
lock.writeLock().lock();
System.out.println(Thread.currentThread().getName() + " 获取到写锁 " + System.currentTimeMillis());
Thread.sleep(5000);
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.writeLock().unlock();
}
}
public static void main(String[] args) {
final Service service = new Service();
Thread threadA = new Thread(new Runnable() {
@Override
public void run() {
service.read();
}
});
Thread threadB = new Thread(new Runnable() {
@Override
public void run() {
service.write();
}
});
threadA.start();
threadB.start();
}
}
Thread-0 获取到读锁 1593756165771
Thread-1 获取到写锁 1593756170771
修改以上代码的main方法如下:
public static void main(String[] args) throws InterruptedException {
final Service service = new Service();
Thread threadA = new Thread(new Runnable() {
@Override
public void run() {
service.read();
}
});
Thread threadB = new Thread(new Runnable() {
@Override
public void run() {
service.write();
}
});
threadB.start();
Thread.sleep(1000);
threadA.start();
}
Thread-1 获取到写锁 1593756318244
Thread-0 获取到读锁 1593756323244
从以上实验结果看来,“读写”,“写读”,“写写”都是互斥的,“读读”是异步非互斥的。
《Java多线程编程核心技术》高红岩