一,简述
在JDK5中增加了Lock锁接口,有ReenTrantLock实现类,ReentranLock锁为可重入锁,它功能比synchronized多。
二,锁的可重入性
锁的可重入是指,当一个线程获得一个对象锁后,再次请求该对象锁时是可以获得该对象的锁的。
/**
* Author: DRHJ
* Date: 2022/7/20 21:48
*/
public class Test01 {
public synchronized void sm1() {
System.out.println("同步方法1");
//线程执行sm1()方法,默认this作为锁对象,在sm1()方法中调用sm2()方法,注意当前线程还是持有this锁对象的
//sm2()同步方法默认锁对象也是this对象,要执行sm2()必须获得this锁对象,当前this对象被当前线程持有,可以再次获得this对象,这就是锁的可重入性。
//如果锁不可重入的话,可能会造成死锁
sm2();
}
public synchronized void sm2() {
System.out.println("同步方法2");
sm3();
}
public synchronized void sm3() {
System.out.println("同步方法3");
}
public static void main(String[] args) {
Test01 obj = new Test01();
new Thread(()-> obj.sm1()).start();
}
}
/**
* ReentrantLock锁的可重入性
* Author: DRHJ
* Date: 2022/7/21 20:46
*/
public class Test04 {
public static void main(String[] args) throws InterruptedException {
SubThread t1 = new SubThread();
SubThread t2 = new SubThread();
t1.start();
t2.start();
t1.join();
t2.join();
System.out.println(SubThread.num);
}
static class SubThread extends Thread {
private static Lock lock = new ReentrantLock();
public static int num = 0;
@Override
public void run() {
for (int i = 0; i < 10000; i++) {
try {
//可重入锁指可以反复获得该锁
lock.lock();
lock.lock();
num++;
} finally {
lock.unlock();
lock.unlock();
}
}
}
}
}
三,ReentranLock
1,基本使用
调用lock()获得锁,调用unlock()释放锁。
/**
* Lock锁的基本使用
* Author: DRHJ
* Date: 2022/7/20 21:59
*/
public class Test02 {
//定义显示锁
static Lock lock = new ReentrantLock();
//定义方法
public static void sm() {
//先获得锁
lock.lock();
for (int i = 0; i < 100; i++) {
System.out.println(Thread.currentThread().getName() + " -- " + i);
}
//释放锁
lock.unlock();
}
public static void main(String[] args) {
Runnable r = () -> sm();
new Thread(r).start();
new Thread(r).start();
new Thread(r).start();
}
}
在不同方法中同步代码块
/**
* 使用Lock锁同步不同方法中的同步代码块
* Author: DRHJ
* Date: 2022/7/20 22:04
*/
public class Test03 {
static Lock lock = new ReentrantLock(); //定义锁对象
public static void sm1() {
//经常在try代码块中获得Lock锁,在finally子句中释放锁
try {
lock.lock(); //获得锁
System.out.println(Thread.currentThread().getName() + " -- method 1 -- " + System.currentTimeMillis());
Thread.sleep(new Random().nextInt(1000));
System.out.println(Thread.currentThread().getName() + " -- method 1 -- " + System.currentTimeMillis());
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock(); //释放锁
}
}
public static void sm2() {
//经常在try代码块中获得Lock锁,在finally子句中释放锁
try {
lock.lock(); //获得锁
System.out.println(Thread.currentThread().getName() + " -- method 2 -- " + System.currentTimeMillis());
Thread.sleep(new Random().nextInt(1000));
System.out.println(Thread.currentThread().getName() + " -- method 2 -- " + System.currentTimeMillis());
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock(); //释放锁
}
}
public static void main(String[] args) {
Runnable r1 = ()-> sm1();
Runnable r2 = ()-> sm2();
new Thread(r1).start();
new Thread(r1).start();
new Thread(r1).start();
new Thread(r2).start();
new Thread(r2).start();
new Thread(r2).start();
}
}
这里作用同synchronized
2,lockInterruptibly()
2.1,基本使用
lockInterruptibly()方法的作用:如果当前线程未被中断则获得锁,如果当前线程被中断出现异常。
/**
* lockInterruptibly()方法的作用:如果当前线程未被中断则获得锁,如果当前线程被中断则出现异常
* Author: DRHJ
* Date: 2022/7/21 21:24
*/
public class Test05 {
public static void main(String[] args) throws InterruptedException {
Service s = new Service();
Runnable r = () -> {
s.serviceMethod();;
};
Thread t1 = new Thread(r);
t1.start();
Thread.sleep(50);
Thread t2 = new Thread(r);
t2.start();
Thread.sleep(50);
t2.interrupt(); //中断t2线程
}
static class Service {
private Lock lock = new ReentrantLock(); //获得锁定,即使调用了线程的interrupt()方法,也没有真正的中断线程
public void serviceMethod() {
try {
lock.lock();
System.out.println(Thread.currentThread().getName() + " -- begin lock");
//执行一段耗时操作
for (int i = 0; i < Integer.MAX_VALUE; i++) {
new StringBuilder();
}
System.out.println(Thread.currentThread().getName() + " -- end lock");
} finally {
lock.unlock();
System.out.println(Thread.currentThread().getName() + " ******* 释放锁");
}
}
}
}
即使中断了,也没有真正中断线程
/**
* lockInterruptibly()方法的作用:如果当前线程未被中断则获得锁,如果当前线程被中断则出现异常
* Author: DRHJ
* Date: 2022/7/21 21:24
*/
public class Test05 {
public static void main(String[] args) throws InterruptedException {
Service s = new Service();
Runnable r = () -> {
s.serviceMethod();;
};
Thread t1 = new Thread(r);
t1.start();
Thread.sleep(50);
Thread t2 = new Thread(r);
t2.start();
Thread.sleep(50);
t2.interrupt(); //中断t2线程
}
static class Service {
private Lock lock = new ReentrantLock(); //获得锁定,即使调用了线程的interrupt()方法,也没有真正的中断线程
public void serviceMethod() {
try {
//lock.lock();
lock.lockInterruptibly(); //如果发生中断,不会获得锁,会发生锁
System.out.println(Thread.currentThread().getName() + " -- begin lock");
//执行一段耗时操作
for (int i = 0; i < Integer.MAX_VALUE; i++) {
new StringBuilder();
}
System.out.println(Thread.currentThread().getName() + " -- end lock");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println(Thread.currentThread().getName() + " ******* 释放锁");
lock.unlock();
}
}
}
}
2.2,解决死锁问题
对于synchronized内部锁来说,如果一个线程在等待锁,只有两个结果:要么该线程获得锁继续执行;要么就保持等待。
对于ReentrantLock可重入锁来说,提供另外一种可能,在等待锁的过程中,程序可以根据需要取消对锁的请求。
package com.drhj.lock.reentrant;
import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Author: DRHJ
* Date: 2022/7/23 17:29
*/
public class Test06 {
public static void main(String[] args) {
IntLock i1 = new IntLock(11);
IntLock i2 = new IntLock(22);
Thread t1 = new Thread(i1);
Thread t2 = new Thread(i2);
t1.start();
t2.start();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
static class IntLock implements Runnable {
public static Lock lock1 = new ReentrantLock();
public static Lock lock2 = new ReentrantLock();
int lockNum; //定义整数变量,决定使用哪个锁
public IntLock(int lockNum) {
this.lockNum = lockNum;
}
@Override
public void run() {
try {
if (lockNum % 2 == 1) {
lock1.lock();
System.out.println(Thread.currentThread().getName() + "获得锁1,还需要获得锁2");
Thread.sleep(new Random().nextInt(500));
lock2.lock();
System.out.println(Thread.currentThread().getName() + "同时获得了锁1与锁2...");
} else {
lock2.lock();
System.out.println(Thread.currentThread().getName() + "获得了锁2,还需要获得锁1");
Thread.sleep(new Random().nextInt(500));
lock1.lock();
System.out.println(Thread.currentThread().getName() + "同时获得了锁1与锁2...");
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock1.unlock();
lock2.unlock();
System.out.println(Thread.currentThread().getName() + "线程退出");
}
}
}
}
可见,发生了死锁。
package com.drhj.lock.reentrant;
import java.util.Random;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 通过ReentrantLock锁的LockInterruptibly()方法避免死锁
* Author: DRHJ
* Date: 2022/7/23 17:29
*/
public class Test06 {
public static void main(String[] args) {
IntLock i1 = new IntLock(11);
IntLock i2 = new IntLock(22);
Thread t1 = new Thread(i1);
Thread t2 = new Thread(i2);
t1.start();
t2.start();
try {
Thread.sleep(3000);
} catch (InterruptedException e) {
e.printStackTrace();
}
//中断其中一个线程来解决死锁
if (t2.isAlive()) t2.interrupt();
}
static class IntLock implements Runnable {
public static ReentrantLock lock1 = new ReentrantLock();
public static ReentrantLock lock2 = new ReentrantLock();
int lockNum; //定义整数变量,决定使用哪个锁
public IntLock(int lockNum) {
this.lockNum = lockNum;
}
@Override
public void run() {
try {
if (lockNum % 2 == 1) {
lock1.lockInterruptibly();
System.out.println(Thread.currentThread().getName() + "获得锁1,还需要获得锁2");
Thread.sleep(new Random().nextInt(500));
lock2.lockInterruptibly();
System.out.println(Thread.currentThread().getName() + "同时获得了锁1与锁2...");
} else {
lock2.lockInterruptibly();
System.out.println(Thread.currentThread().getName() + "获得了锁2,还需要获得锁1");
Thread.sleep(new Random().nextInt(500));
lock1.lockInterruptibly();
System.out.println(Thread.currentThread().getName() + "同时获得了锁1与锁2...");
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (lock1.isHeldByCurrentThread()) //如果被当前线程持有
lock1.unlock();
if (lock2.isHeldByCurrentThread())
lock2.unlock();
System.out.println(Thread.currentThread().getName() + "线程退出");
}
}
}
}
3,tryLock()方法
tryLock(long time, TimeUnit unit)的作用在给定等待时长内锁没有被另外的线程持有,并且当前线程也没有被中断,则获得该锁。通过该方法实现锁对象的限时等待。
3.1,基本使用
package com.drhj.lock.reentrant;
import java.sql.Time;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;
/**
* tryLock的基本使用
* Author: DRHJ
* Date: 2022/7/23 19:46
*/
public class Test07 {
public static void main(String[] args) {
TimeLock timeLock = new TimeLock();
Thread t1 = new Thread(timeLock);
Thread t2 = new Thread(timeLock);
t1.start();
t2.start();
}
static class TimeLock implements Runnable {
private static ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
try {
if (lock.tryLock(3, TimeUnit.SECONDS)) {
System.out.println(Thread.currentThread().getName() + "获得锁,执行耗时任务");
Thread.sleep(4000);
} else {
System.out.println(Thread.currentThread().getName() + "没有获得锁");
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (lock.isHeldByCurrentThread())
lock.unlock();
}
}
}
}
线程Thread-1拿到执行权后需要睡眠4s,而线程Thread-0在Thread-1拿到执行权的后一步拿到执行权时,Thread-1在睡眠,导致Thread-0在3s内没有拿到锁,因此返回没有获得锁。
tryLock()仅在调用时锁定未被其他线程持有的锁,如果调用方法时,锁对象为其他线程持有,则放弃。调用方法尝试获得锁,如果该锁没有被其他线程占用则返回true表示锁定成功;如果锁被其他线程占用则返回false,不等待。
package com.drhj.lock.reentrant;
import java.util.concurrent.locks.ReentrantLock;
/**
* tryLock()当锁对象没有被其他线程持有的情况下才会获得该线程
* Author: DRHJ
* Date: 2022/7/26 20:25
*/
public class Test08 {
public static void main(String[] args) throws InterruptedException {
Service s = new Service();
Runnable r = () -> s.serviceMethod();
Thread t1 = new Thread(r);
t1.start();
Thread.sleep(50);
Thread t2 = new Thread(r);
t2.start();
}
static class Service {
private ReentrantLock lock = new ReentrantLock();
public void serviceMethod() {
try {
if (lock.tryLock()) {
System.out.println(Thread.currentThread().getName() + "获得锁定");
Thread.sleep(3000); //模拟执行任务的时长
} else {
System.out.println(Thread.currentThread().getName() + "没有获得锁定");
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (lock.isHeldByCurrentThread()) {
lock.unlock();
}
}
}
}
}
3.2,避免死锁
package com.drhj.lock.reentrant;
import java.util.Random;
import java.util.concurrent.locks.ReentrantLock;
/**
* 使用tryLock()可以避免死锁
* Author: DRHJ
* Date: 2022/7/27 19:53
*/
public class Test09 {
public static void main(String[] args) {
IntLock intLock1 = new IntLock(11);
IntLock intLock2 = new IntLock(12);
Thread t1 = new Thread(intLock1);
Thread t2 = new Thread(intLock2);
t1.start();
t2.start();
//运行后,使用tryLock()尝试获得锁,不会傻傻的等待,通过循环不停的再次尝试,如果通过的时间足够长,是会同时获得两个锁
}
static class IntLock implements Runnable {
private static ReentrantLock lock1 = new ReentrantLock();
private static ReentrantLock lock2 = new ReentrantLock();
private int lockNum; //用于控制锁的顺序
public IntLock(int lockNum) {
this.lockNum = lockNum;
}
@Override
public void run() {
if (lockNum % 2 == 0) { //偶数先锁1,再锁2
while (true) {
try {
if (lock1.tryLock()) {
System.out.println(Thread.currentThread().getName() + "获得锁1,还想获得锁2");
Thread.sleep(new Random().nextInt(100));
try {
if (lock2.tryLock()) {
System.out.println(Thread.currentThread().getName() + "同时获得锁1与锁2---完成任务");
return; //结束run方法
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (lock2.isHeldByCurrentThread()) {
lock2.unlock();
}
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (lock1.isHeldByCurrentThread()) {
lock1.unlock();
}
}
}
} else { //奇数先锁2,再锁1
while (true) {
try {
if (lock2.tryLock()) {
System.out.println(Thread.currentThread().getName() + "获得锁2,还想获得锁1");
Thread.sleep(new Random().nextInt(100));
try {
if (lock1.tryLock()) {
System.out.println(Thread.currentThread().getName() + "同时获得锁1与锁2---完成任务");
return; //结束run方法
}
} catch (Exception e) {
e.printStackTrace();
} finally {
if (lock1.isHeldByCurrentThread()) {
lock1.unlock();
}
}
}
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (lock2.isHeldByCurrentThread()) {
lock2.unlock();
}
}
}
}
}
}
}
使用tryLock(),当前锁被其他锁占用,则不等待,因此不会出现死锁,当上述线程执行时间够长或得睡眠时间比较小,线程能够顺利执行结束。
4,newCondition()方法
关键字synchronized与wait()/notify()这两个方法一起使用可以实现等待/通知模式。Lock锁的newCondition()方法返回Condition对象,Condition类也可以实现等待/通知模式。
使用notify()通知时,JVM会随时唤醒某个等待的线程。使用Condition类可以进行选择性通知。Condition比较常用的两个方法:
await()会使当前线程等待,同时会释放锁,当其他线程调用signal()时,线程会重新获得锁并继续执行。
signal()用于唤醒一个等待的线程
注意:在调用Condition的await()/signal()方法前,也需要线程持有相关的Lock锁。调用await()后线程会释放这个锁,在signal()调用会从当前Condition对象的等待队列中,唤醒一个线程,唤醒的线程尝试获得锁,一旦获得锁成功就继续执行。
4.1,基本使用
package com.drhj.lock.condition;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* Condition等待与通知
* Author: DRHJ
* Date: 2022/7/27 20:37
*/
public class Test01 {
//定义锁
static Lock lock = new ReentrantLock();
//获得Condition对象
static Condition condition = lock.newCondition();
public static void main(String[] args) throws InterruptedException {
SubThread t = new SubThread();
t.start();
//子线程启动后,会转入等待状态
Thread.sleep(3000);
//主线程在睡眠3s后,唤醒子线程的等待
try {
lock.lock();
condition.signal();
} finally {
lock.unlock();
}
}
//定义线程子类
static class SubThread extends Thread {
@Override
public void run() {
try {
lock.lock(); //调用await()前必须先获得锁
System.out.println("method lock");
condition.await(); //等待
System.out.println("method await");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock(); //释放锁
System.out.println("method unlock");
}
}
}
}
线程唤醒
4.2,实现通知部分线程
package com.drhj.lock.condition;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* 多个Condition实现通知部分线程
* Author: DRHJ
* Date: 2022/7/28 19:16
*/
public class Test02 {
public static void main(String[] args) throws InterruptedException {
Service service = new Service();
new Thread(()-> service.waitMethodA()).start();
new Thread(()-> service.waitMethodB()).start();
Thread.sleep(3000);
//service.signalA();
service.signalB();
}
static class Service {
private ReentrantLock lock = new ReentrantLock();
private Condition conditionA = lock.newCondition();
private Condition conditionB = lock.newCondition();
//定义方法,使用conditionA等待
public void waitMethodA() {
try {
lock.lock();
System.out.println(Thread.currentThread().getName() + " begin wait: " + System.currentTimeMillis());
conditionA.await();
System.out.println(Thread.currentThread().getName() + " end wait: " + System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
//定义方法,使用conditionB等待
public void waitMethodB() {
try {
lock.lock();
System.out.println(Thread.currentThread().getName() + " begin wait: " + System.currentTimeMillis());
conditionB.await();
System.out.println(Thread.currentThread().getName() + " end wait: " + System.currentTimeMillis());
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
//定义方法唤醒conditionA对象上的等待
public void signalA() {
try {
lock.lock();
System.out.println(Thread.currentThread().getName() + " signal A time = " + System.currentTimeMillis());
conditionA.signal();
System.out.println(Thread.currentThread().getName() + " signal A time = " + System.currentTimeMillis());
} finally {
lock.unlock();
}
}
//定义方法唤醒conditionB对象上的等待
public void signalB() {
try {
lock.lock();
System.out.println(Thread.currentThread().getName() + " signal B time = " + System.currentTimeMillis());
conditionB.signal();
System.out.println(Thread.currentThread().getName() + " signal B time = " + System.currentTimeMillis());
} finally {
lock.unlock();
}
}
}
}
可见,A线程继续等待,B线程执行完成。
4.2,两个线程交替打印
package com.drhj.lock.condition;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 使用Condition实现生产者/消费者设计模式,两个线程交替打印
* Author: DRHJ
* Date: 2022/7/28 20:33
*/
public class Test03 {
public static void main(String[] args) {
MyService myService = new MyService();
//创建线程打印
new Thread(()-> {
for (int i = 0; i < 100; i++) {
myService.printOne();
}
}).start();
new Thread(()->{
for (int i = 0; i < 100; i++) {
myService.printTwo();
}
}).start();
}
static class MyService {
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
private boolean flag = true;
public void printOne() {
try {
lock.lock();
while (flag) {
System.out.println(Thread.currentThread().getName() + " waiting...");
condition.await();
}
System.out.println(Thread.currentThread().getName() + " ------------ ");
flag = true;
condition.signal(); //通知另外的线程打印
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void printTwo() {
try {
lock.lock();
while (!flag) {
System.out.println(Thread.currentThread().getName() + " waiting...");
condition.await();
}
System.out.println(Thread.currentThread().getName() + " ************ ");
flag = false;
condition.signal(); //通知另外的线程打印
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}
交替执行
4.3,多对多生产者与消费者模式
package com.drhj.lock.condition;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 使用Condition实现生产者/消费者设计模式,多对多,即有多个线程打印----,有多个线程打印**,实现--与**交替打印
* Author: DRHJ
* Date: 2022/7/30 20:11
*/
public class Test04 {
public static void main(String[] args) {
MyService myService = new MyService();
for (int j = 0; j < 10; j++) {
//创建线程打印
new Thread(()-> {
for (int i = 0; i < 100; i++) {
myService.printOne();
}
}).start();
new Thread(()->{
for (int i = 0; i < 100; i++) {
myService.printTwo();
}
}).start();
}
}
static class MyService {
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
private boolean flag = true;
public void printOne() {
try {
lock.lock();
while (flag) {
System.out.println(Thread.currentThread().getName() + " waiting...");
condition.await();
}
System.out.println(Thread.currentThread().getName() + " ------------ ");
flag = true;
condition.signal(); //通知另外的线程打印
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void printTwo() {
try {
lock.lock();
while (!flag) {
System.out.println(Thread.currentThread().getName() + " waiting...");
condition.await();
}
System.out.println(Thread.currentThread().getName() + " ************ ");
flag = false;
condition.signal(); //通知另外的线程打印
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}
发生死锁,也是因为锁唤醒了同伴导致的问题
package com.drhj.lock.condition;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
/**
* 使用Condition实现生产者/消费者设计模式,多对多,即有多个线程打印----,有多个线程打印**,实现--与**交替打印
* Author: DRHJ
* Date: 2022/7/30 20:11
*/
public class Test04 {
public static void main(String[] args) {
MyService myService = new MyService();
for (int j = 0; j < 10; j++) {
//创建线程打印
new Thread(()-> {
for (int i = 0; i < 100; i++) {
myService.printOne();
}
}).start();
new Thread(()->{
for (int i = 0; i < 100; i++) {
myService.printTwo();
}
}).start();
}
}
static class MyService {
private Lock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
private boolean flag = true;
public void printOne() {
try {
lock.lock();
while (flag) {
System.out.println(Thread.currentThread().getName() + " waiting...");
condition.await();
}
System.out.println(Thread.currentThread().getName() + " ------------ ");
flag = true;
condition.signalAll(); //通知另外的线程打印
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void printTwo() {
try {
lock.lock();
while (!flag) {
System.out.println(Thread.currentThread().getName() + " waiting...");
condition.await();
}
System.out.println(Thread.currentThread().getName() + " ************ ");
flag = false;
condition.signalAll(); //通知另外的线程打印
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
}
唤醒所有
5,公平锁与非公平锁
大多数情况下,锁的申请都是非公平的。如果线程1与线程2都在请求锁A,当锁A可用时,系统只是会从阻塞队列中随机选择一个线程,不能保证其公平性。
公平的锁会按照时间的先后顺序,保证先到先得,公平锁的这一特点不会出现线程饥饿现象。
synchronized内部锁就是非公平的,ReentranLock重入锁提供了一个构造方法:ReentrantLock(boolean fair),当在创建锁对象时实参传递true可以把该锁设置为公平锁。公平锁看起来很公平,但是要实现公平锁必须要求系统维护一个有序队列,公平锁的实现成本较高,性能也低,因此默认情况下锁是非公平的,不是特别的需求,一般不使用公平锁。
实例
默认是非公平锁
package com.drhj.lock.method;
import java.util.concurrent.locks.ReentrantLock;
/**
* 公平锁与非公平锁
* Author: DRHJ
* Date: 2022/7/31 17:56
*/
public class Test01 {
static ReentrantLock lock = new ReentrantLock(); //默认为非公平锁
public static void main(String[] args) {
Runnable r = () -> {
while (true) {
try {
lock.lock();
System.out.println(Thread.currentThread().getName() + "获得了锁对象");
} finally {
lock.unlock();
}
}
};
for (int i = 0; i < 5; i++) {
new Thread(r).start();
}
}
}
非公平锁,线程会倾向于让一个线程再次获得已经持有的锁,这种分配策略是高效的,但是是非公平
设置公平锁
package com.drhj.lock.method;
import java.util.concurrent.locks.ReentrantLock;
/**
* 公平锁与非公平锁
* Author: DRHJ
* Date: 2022/7/31 17:56
*/
public class Test01 {
static ReentrantLock lock = new ReentrantLock(true); //默认为非公平锁
public static void main(String[] args) {
Runnable r = () -> {
while (true) {
try {
lock.lock();
System.out.println(Thread.currentThread().getName() + "获得了锁对象");
} finally {
lock.unlock();
}
}
};
for (int i = 0; i < 5; i++) {
new Thread(r).start();
}
}
}
公平锁,对个线程不会发生同一个线程连续多次获得锁的可能,保证锁的公平性
6,常用方法
6.1,getHoldCount()
getHoldCount()返回当前线程调用lock()方法的次数
package com.drhj.lock.method;
import java.util.concurrent.locks.ReentrantLock;
/**
* getHoldCount()方法可以返回当前线程调用lock()方法的次数
* Author: DRHJ
* Date: 2022/7/31 18:17
*/
public class Test02 {
static ReentrantLock lock = new ReentrantLock(); //定义锁对象
public static void main(String[] args) {
m1();
}
public static void m1() {
try {
lock.lock();
System.out.println(Thread.currentThread().getName() + " -- hold count : " + lock.getHoldCount());
m2();
} finally {
lock.unlock();
}
}
public static void m2() {
try {
lock.lock();
System.out.println(Thread.currentThread().getName() + " -- hold count : " + lock.getHoldCount());
} finally {
lock.unlock();
}
}
}
6.2,getQueueLength()
getQueueLength()返回正等待获得锁的线程预估数
package com.drhj.lock.method;
import java.util.concurrent.locks.ReentrantLock;
/**
* getQueueLength()返回等待获得锁的线程预估数
* Author: DRHJ
* Date: 2022/7/31 18:25
*/
public class Test03 {
static ReentrantLock lock = new ReentrantLock();
public static void main(String[] args) {
Runnable r = Test03::sum;
for (int i = 0; i < 10; i++) {
new Thread(r).start();
}
}
public static void sum() {
try {
lock.lock();
System.out.println(Thread.currentThread().getName() + "获得锁,执行方法,估计等待获得锁的线程数: " + lock.getQueueLength());
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
6.3,getWaitQueueLength(Condition condition)
getWaitQueueLength(Condition condition)返回与Condition条件相关的等待线程预估数
package com.drhj.lock.method;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* getWaitQueueLength(Condition condition)返回再Condition条件上等待的线程预估数
* Author: DRHJ
* Date: 2022/7/31 18:31
*/
public class Test04 {
public static void main(String[] args) throws InterruptedException {
Service service = new Service();
Runnable r = () -> service.waitMethod();
for (int i = 0; i < 10; i++) {
new Thread(r).start();
}
Thread.sleep(2000);
service.notifyMethod();
}
static class Service {
private ReentrantLock lock = new ReentrantLock();
private Condition condition = lock.newCondition();
public void waitMethod() {
try {
lock.lock();
System.out.println(Thread.currentThread().getName() + " 进入等待前,现在该Condition条件等待的线程预估数: " + lock.getWaitQueueLength(condition));
condition.await();
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void notifyMethod() {
try {
lock.lock();
condition.signalAll();
System.out.println("唤醒所有的等待线程后,condition条件上等待的线程预估数: " + lock.getWaitQueueLength(condition));
} finally {
lock.unlock();
}
}
}
}
6.4,hasQueuedThread(Thread thread)/hasQueuedThreads()
hasQueueThread(Thread thread)查询参数指定的线程是否在等待获得锁
hasQueuedThreads()查询是否还有在等待获得该锁
package com.drhj.lock.method;
import java.util.concurrent.locks.ReentrantLock;
/**
* hasQueuedThread(Thread thread)查询指定的线程在等待获得锁
* hasQueuedThreads() 查询是否有线程在等待获得锁
* Author: DRHJ
* Date: 2022/7/31 18:44
*/
public class Test05 {
static ReentrantLock lock = new ReentrantLock();
public static void main(String[] args) throws InterruptedException {
Runnable r = Test05::waitMethod;
Thread [] threads = new Thread[5];
for (int i = 0; i < threads.length; i++) {
threads[i] = new Thread(r);
threads[i].setName("thread - " + i);
threads[i].start();
}
Thread.sleep(3000);
//判断数组中的每个线程是否正在等待获得锁
System.out.println("线程 - 0 : " + lock.hasQueuedThread(threads[0]));
System.out.println("线程 - 1 : " + lock.hasQueuedThread(threads[1]));
System.out.println("线程 - 2 : " + lock.hasQueuedThread(threads[2]));
System.out.println("线程 - 3 : " + lock.hasQueuedThread(threads[3]));
System.out.println("线程 - 4 : " + lock.hasQueuedThread(threads[4]));
Thread.sleep(2000);
//再次判断是否还有线程在等待获得该锁
System.out.println(lock.hasQueuedThreads());
}
public static void waitMethod() {
try {
lock.lock();
System.out.println(Thread.currentThread().getName() + "获得了锁");
Thread.sleep(1000);
} catch (Exception e) {
e.printStackTrace();
} finally {
lock.unlock();
System.out.println(Thread.currentThread().getName() + " 释放了锁对象......");
}
}
}
6.5,hasWaiters(Condition condition)
hasWaiters(Condition condition)查询是否有线程正在等待指定的Condition条件
package com.drhj.lock.method;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
/**
* hasWaiters(Condition condition)查询是否有指定的condition条件
* Author: DRHJ
* Date: 2022/8/2 21:10
*/
public class Test06 {
static ReentrantLock lock = new ReentrantLock(); //创建锁对象
static Condition condition = lock.newCondition();
public static void main(String[] args) {
Runnable r = Test06::sm;
for (int i = 0; i < 10; i++) {
new Thread(r).start();
}
}
static void sm() {
try {
lock.lock();
System.out.println(Thread.currentThread().getName() + " lock...");
System.out.println("是否有线程正在等待当前Condition条件? " + lock.hasWaiters(condition) + " --waitqueuelenth: " + lock.getWaitQueueLength(condition));
condition.await(new Random().nextInt(1000), TimeUnit.MICROSECONDS); //超时后自动唤醒
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println(Thread.currentThread().getName() + " unlock... ");
lock.unlock();
}
}
}
6.6,isFair()/isHeldByCurrentThread()
isFair()判断是否为公平锁
isHeldByCurrentThread()判断当前线程是否持有该锁
package com.drhj.lock.method;
import java.util.Random;
import java.util.concurrent.locks.ReentrantLock;
/**
* isFair()判断是否为公平锁
* isHeldByCurrentThread()判断当前线程是否持有该锁
* Author: DRHJ
* Date: 2022/8/2 21:28
*/
public class Test07 {
public static void main(String[] args) {
Runnable r = ()-> {
int num = new Random().nextInt();
new Service(num % 2 == 0) .serviceMethod();
};
for (int i = 0; i < 3; i++) {
new Thread(r).start();
}
}
static class Service {
private ReentrantLock lock;
public Service(boolean isFair) {
this.lock = new ReentrantLock(isFair);
}
public void serviceMethod() {
try {
System.out.println("是否公平锁? " + lock.isFair() + " -- " + Thread.currentThread().getName() + " 调用lock前是否持有锁? " + lock.isHeldByCurrentThread());
lock.lock();
System.out.println(Thread.currentThread().getName() + " 调用lock方法后是否持有锁? " + lock.isHeldByCurrentThread());
} finally {
if (lock.isHeldByCurrentThread())
lock.unlock();
}
}
}
}
6.6,isLocked()
isLocked()当前锁是否被线程持有
package com.drhj.lock.method;
import java.util.concurrent.locks.ReentrantLock;
/**
* isLocked()当前锁是否被线程持有
* Author: DRHJ
* Date: 2022/8/2 21:38
*/
public class Test08 {
static ReentrantLock lock = new ReentrantLock();
public static void main(String[] args) throws InterruptedException {
System.out.println(" 11 -- " + lock.isLocked());
new Thread(Test08::sm).start();
Thread.sleep(3000); //确保子线程执行结束
System.out.println(" 22 --- " + lock.isLocked());
}
static void sm() {
try {
System.out.println(" before lock() -- " + lock.isLocked());
lock.lock();
System.out.println(" after lock() -- " + lock.isLocked());
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
if (lock.isHeldByCurrentThread())
lock.unlock();
}
}
}
四,ReentrantReadWriterLock
1,概述
synchronized内部锁与ReentrantLock锁都是独占锁(排它锁),同一时间只允许一个线程执行同步代码块,可以保证线程的安全性,但是执行效率低。
ReentrantReadWriterLock读写锁是一种改进的排它锁,也可以称作共享/排它锁。允许多个线程同时读取共享数据,但是一次只允许一个线程对共享数据进行更新。
读写锁通过读锁与写锁来完成读写操作。线程在读取共享数据前必须先持有读锁,该读锁可以同时被多个线程持有,即它是共享的;写锁是排它的,线程在修改共享数据前必须先持有写锁,一个线程持有写锁时其他线程无法获得相应的锁(包括读锁)。
读锁只是在读线程之间共享,任何一个线程持有读锁时,其他线程都无法获得写锁,保证线程在读取数据期间没有其他线程对数据进行更新,使得读线程能够读到数据的最新值,保证在读数据期间共享变量不被修改
获得条件 | 排它性 | 作用 | |
---|---|---|---|
读锁 | 写锁未被任意线程持有 | 对读线程是共享的,对写线程是排它 | 允许多个读线程可以同时读取共享数据,保证在读共享数据时,没有其他线程对共享数据进行修改 |
写锁 | 该写锁未被其他线程持有,并且相应的读锁也未被其他线程持有 | 对读线程或者写线程都是排它的 | 保证写线程以独占的方式修改共享数据 |
读写锁允许读读共享,读写互斥,写写互斥。
在java.util.concurrent.locks包中定义了ReadWriterLock接口,该接口中定义了readLock()返回读锁,定义writeLock()方法返回写锁。该接口的实现类是ReentrantReadWriteLock。
注意readLock()与writeLock()方法返回的锁对象是同一个锁的两个不同的角色,不是分别获得两个不同的锁。ReadWriteLock接口实例可以充当两个角色。读写锁的其他使用方法
//定义读写锁
ReadWriteLock rwLock = new ReentrantReadWriteLock()
//定义读锁
Lock readLock = rwLock.readLock();
//定义写锁
Lock writeLock = rwLock.writeLock();
//读数据
readLock.lock(); //申请读锁
try {
读取共享数据
} finally {
readLock.unlock(); //总是在finally子句中释放锁
}
//写数据
writeLock.lock(); //申请读锁
try {
更新修改共享数据
} finally {
writeLock.unlock(); //总是在finally子句中释放锁
}
2,读读共享
ReadWriteLock读写锁可以实现多个线程同时读取共享数据,即读读共享,可以提高程序的读取数据的效率。
package com.drhj.lock.readwrite;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* ReadWriteLock读写锁可以实现读读共享,允许多个线程同时获得读锁
* Author: DRHJ
* Date: 2022/8/3 22:06
*/
public class Test01 {
public static void main(String[] args) {
Service service = new Service();
for (int i = 0; i < 5; i++) {
new Thread(()-> service.read()).start();
}
}
static class Service {
//定义读写锁
ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
//定义方法读取数据
public void read() {
try {
readWriteLock.readLock().lock(); //获得读锁
System.out.println(Thread.currentThread().getName() + "获得读锁 -- " + System.currentTimeMillis());
TimeUnit.SECONDS.sleep(3); //模拟读取数据用时
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
readWriteLock.readLock().unlock(); //释放读锁
}
}
}
}
可以读取时间基本一致
3,写写互斥
通过ReadWriteLock读写锁中的写锁,只允许有一个线程执行lock()后面的代码。
package com.drhj.lock.readwrite;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* 演示ReadWriteLock的writeLock()写锁是互斥的,只允许有一个线程持有
* Author: DRHJ
* Date: 2022/8/3 22:41
*/
public class Test02 {
public static void main(String[] args) {
Service service = new Service();
for (int i = 0; i < 5; i++) {
new Thread(()->service.write()).start();
}
}
static class Service {
//先定义读写锁
ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
//定义方法修改数据
public void write() {
try {
readWriteLock.writeLock().lock(); //申请获得写锁
System.out.println(Thread.currentThread().getName() + "获得写锁,开始修改数据的时间 -- " + System.currentTimeMillis());
Thread.sleep(3000); //模仿修改数据用时
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println(Thread.currentThread().getName() + "读取数据完毕时的时间 == " + System.currentTimeMillis());
readWriteLock.writeLock().unlock();
}
}
}
}
可见每个线程都是执行完3s后,另一个线程才拿到写锁。
4,读写互斥
写锁时独占锁,是排它锁,读线程与写线程也是互斥的。
package com.drhj.lock.readwrite;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
* 演示ReadWriteLock的读写互斥
* 一个线程获得读锁时,写线程等待;一个线程获得写锁时,其他线程等待
* Author: DRHJ
* Date: 2022/8/4 21:35
*/
public class Test03 {
public static void main(String[] args) {
Service service = new Service();
new Thread(()->{
service.read();
}).start();
new Thread(()->{
service.write();
}).start();
}
static class Service {
//先定义读写锁
ReadWriteLock readWriteLock = new ReentrantReadWriteLock();
//读取数据
public void read() {
try {
readWriteLock.readLock().lock(); //申请获得读锁
System.out.println(Thread.currentThread().getName() + "获得读锁,开始读取数据的时间 -- " + System.currentTimeMillis());
Thread.sleep(3000); //模仿修改数据用时
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println(Thread.currentThread().getName() + "读取数据完毕时的时间 == " + System.currentTimeMillis());
readWriteLock.readLock().unlock();
}
}
//定义方法修改数据
public void write() {
try {
readWriteLock.writeLock().lock(); //申请获得写锁
System.out.println(Thread.currentThread().getName() + "获得写锁,开始修改数据的时间 -- " + System.currentTimeMillis());
Thread.sleep(3000); //模仿修改数据用时
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
System.out.println(Thread.currentThread().getName() + "修改数据完毕时的时间 == " + System.currentTimeMillis());
readWriteLock.writeLock().unlock();
}
}
}
}