深入理解ReentrantLock与Condition
锁是什么?
并发编程的时候,比如说有一个业务是读写操作,那多个线程执行这个业务就会造成已经写入的数据又写一遍,就会造成数据错乱。
所以需要引入锁,进行数据同步,强制使得该业务执行的时候只有一个线程在执行,从而保证不会插入多条重复数据。
一些共享资源也是需要加锁,从而保证数据的一致性。
使用ReentrantLock同步
首先来看第一个实例:用两个线程来在控制台有序打出1,2,3。
public class FirstReentrantLock {
public static void main(String[] args) {
Runnable runnable = new ReentrantLockThread();
new Thread(runnable, "a").start();
new Thread(runnable, "b").start();
}
}
class ReentrantLockThread implements Runnable {
@Override
public void run() {
for (int i = 0; i < 3; i++) {
System.out.println(Thread.currentThread().getName() + "输出了: " + i);
}
}
}
执行FirstReentrantLock ,查看控制台输出:
图片.png
可以看到,并没有顺序,杂乱无章。
那使用ReentrantLock加入锁,代码如下:
package com.chapter2;
import java.util.concurrent.locks.ReentrantLock;
/**
* @author tangj
*
* 如何使用ReentrantLock
*/
public class FirstReentrantLock {
public static void main(String[] args) {
Runnable runnable = new ReentrantLockThread();
new Thread(runnable, "a").start();
new Thread(runnable, "b").start();
}
}
class ReentrantLockThread implements Runnable {
// 创建一个ReentrantLock对象
ReentrantLock lock = new ReentrantLock();
@Override
public void run() {
try {
// 使用lock()方法加锁
lock.lock();
for (int i = 0; i < 3; i++) {
System.out.println(Thread.currentThread().getName() + "输出了: " + i);
}
} finally {
// 别忘了执行unlock()方法释放锁
lock.unlock();
}
}
}
执行FirstReentrantLock ,查看控制台输出:
图片.png有顺序的打印出了0,1,2,0,1,2.
这就是锁的作用,它是互斥的,当一个线程持有锁的时候,其他线程只能等待,待该线程执行结束,再通过竞争得到锁。
使用Condition实现线程等待和唤醒
通常在开发并发程序的时候,会碰到需要停止正在执行业务A,来执行另一个业务B,当业务B执行完成后业务A继续执行。ReentrantLock通过Condtion等待/唤醒这样的机制.
通常在开发并发程序的时候,会碰到需要停止正在执行业务A,来执行另一个业务B,当业务B执行完成后业务A继续执行。ReentrantLock通过Condtion等待/唤醒这样的机制.
相比较synchronize的wait()和notify()/notifAll()的机制而言,Condition具有更高的灵活性,这个很关键。Conditon可以实现多路通知和选择性通知。
当使用notify()/notifAll()时,JVM时随机通知线程的,具有很大的不可控性,所以建议使用Condition。
Condition使用起来也非常方便,只需要注册到ReentrantLock下面即可
参考下图:
图片.png
接下来,使用Condition来实现等待/唤醒,并且能够唤醒制定线程
先写业务代码:
package com.chapter2.howtocondition;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class MyService {
// 实例化一个ReentrantLock对象
private ReentrantLock lock = new ReentrantLock();
// 为线程A注册一个Condition
public Condition conditionA = lock.newCondition();
// 为线程B注册一个Condition
public Condition conditionB = lock.newCondition();
public void awaitA() {
try {
lock.lock();
System.out.println(Thread.currentThread().getName() + "进入了awaitA方法");
long timeBefore = System.currentTimeMillis();
// 执行conditionA等待
conditionA.await();
long timeAfter = System.currentTimeMillis();
System.out.println(Thread.currentThread().getName()+"被唤醒");
System.out.println(Thread.currentThread().getName() + "等待了: " + (timeAfter - timeBefore)/1000+"s");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void awaitB() {
try {
lock.lock();
System.out.println(Thread.currentThread().getName() + "进入了awaitB方法");
long timeBefore = System.currentTimeMillis();
// 执行conditionB等待
conditionB.await();
long timeAfter = System.currentTimeMillis();
System.out.println(Thread.currentThread().getName()+"被唤醒");
System.out.println(Thread.currentThread().getName() + "等待了: " + (timeAfter - timeBefore)/1000+"s");
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void signallA() {
try {
lock.lock();
System.out.println("启动唤醒程序");
// 唤醒所有注册conditionA的线程
conditionA.signalAll();
} finally {
lock.unlock();
}
}
public void signallB() {
try {
lock.lock();
System.out.println("启动唤醒程序");
// 唤醒所有注册conditionA的线程
conditionB.signalAll();
} finally {
lock.unlock();
}
}
}
分别实例化了两个Condition对象,都是使用同一个lock注册。注意conditionA对象的等待和唤醒只对使用了conditionA的线程有用,同理conditionB对象的等待和唤醒只对使用了conditionB的线程有用。
继续写两个线程的代码:
package com.chapter2.howtocondition;
public class MyServiceThread1 implements Runnable {
private MyService service;
public MyServiceThread1(MyService service) {
this.service = service;
}
@Override
public void run() {
service.awaitA();
}
}
注意:MyServiceThread1 使用了awaitA()方法,持有的是conditionA!
package com.chapter2.howtocondition;
public class MyServiceThread2 implements Runnable {
private MyService service;
public MyServiceThread2(MyService service) {
this.service = service;
}
@Override
public void run() {
service.awaitB();
}
}
注意:MyServiceThread2 使用了awaitB()方法,持有的是conditionB!
最后看启动类:
package com.chapter2.howtocondition;
public class ApplicationCondition {
public static void main(String[] args) throws InterruptedException {
MyService service = new MyService();
Runnable runnable1 = new MyServiceThread1(service);
Runnable runnable2 = new MyServiceThread2(service);
new Thread(runnable1, "a").start();
new Thread(runnable2, "b").start();
// 线程sleep2秒钟
Thread.sleep(2000);
// 唤醒所有持有conditionA的线程
service.signallA();
Thread.sleep(2000);
// 唤醒所有持有conditionB的线程
service.signallB();
}
}
执行ApplicationCondition ,来看控制台输出结果:
图片.png
a和b都进入各自的await()方法。首先执行的是
图片.png使用conditionA的线程被唤醒,而后再唤醒使用conditionB的线程。
学会使用Condition,那来用它实现生产者消费者模式
生产者和消费者
首先来看业务类的实现:
package com.chapter2.consumeone;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class Service {
private Lock lock = new ReentrantLock();
private boolean flag = false;
private Condition condition = lock.newCondition();
// 以此为衡量标志
private int number = 1;
/**
* 生产者生产
*/
public void produce() {
try {
lock.lock();
while (flag == true) {
condition.await();
}
System.out.println(Thread.currentThread().getName() + "-----生产-----");
number++;
System.out.println("number: " + number);
System.out.println();
flag = true;
// 提醒消费者消费
condition.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
/**
* 消费者消费生产的物品
*/
public void consume() {
try {
lock.lock();
while (flag == false) {
condition.await();
}
System.out.println(Thread.currentThread().getName() + "-----消费-----");
number--;
System.out.println("number: " + number);
System.out.println();
flag = false;
// 提醒生产者生产
condition.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
生产者线程代码:
package com.chapter2.consumeone;
/**
* 生产者线程
*
* @author tangj
*
*/
public class MyThreadProduce implements Runnable {
private Service service;
public MyThreadProduce(Service service) {
this.service = service;
}
@Override
public void run() {
for (;;) {
service.produce();
}
}
}
消费者线程代码:
package com.chapter2.consumeone;
/**
* 消费者线程
*
* @author tangj
*
*/
public class MyThreadConsume implements Runnable {
private Service service;
public MyThreadConsume(Service service) {
super();
this.service = service;
}
@Override
public void run() {
for (;;) {
service.consume();
}
}
}
启动类:
package com.chapter2.consumeone;
public class Application {
public static void main(String[] args) {
Service service = new Service();
Runnable produce = new MyThreadProduce(service);
Runnable consume = new MyThreadConsume(service);
new Thread(produce, "生产者 ").start();
new Thread(consume, "消费者 ").start();
}
}
执行Application,看控制台的输出:
图片.png
因为采用了无限循环,生产者线程和消费者线程会一直处于工作状态,可以看到,生产者线程执行完毕后,消费者线程就会执行,以这样的交替顺序,
而且的number也遵循者生产者生产+1,消费者消费-1的一个状态。这个就是使用ReentrantLock和Condition来实现的生产者消费者模式。
顺序执行线程
充分发掘Condition的灵活性,可以用它来实现顺序执行线程。
来看业务类代码:
package com.chapter2.sequencethread;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class Service {
// 通过nextThread控制下一个执行的线程
private static int nextThread = 1;
private ReentrantLock lock = new ReentrantLock();
// 有三个线程,所有注册三个Condition
Condition conditionA = lock.newCondition();
Condition conditionB = lock.newCondition();
Condition conditionC = lock.newCondition();
public void excuteA() {
try {
lock.lock();
while (nextThread != 1) {
conditionA.await();
}
System.out.println(Thread.currentThread().getName() + " 工作");
nextThread = 2;
conditionB.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void excuteB() {
try {
lock.lock();
while (nextThread != 2) {
conditionB.await();
}
System.out.println(Thread.currentThread().getName() + " 工作");
nextThread = 3;
conditionC.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
public void excuteC() {
try {
lock.lock();
while (nextThread != 3) {
conditionC.await();
}
System.out.println(Thread.currentThread().getName() + " 工作");
nextThread = 1;
conditionA.signalAll();
} catch (InterruptedException e) {
e.printStackTrace();
} finally {
lock.unlock();
}
}
}
这里可以看到,注册了三个Condition,分别用于三个线程的等待和通知。
启动类代码:
package com.chapter2.sequencethread;
/**
* 线程按顺序执行
*
* @author tangj
*
*/
public class Application {
private static Runnable getThreadA(final Service service) {
return new Runnable() {
@Override
public void run() {
for (;;) {
service.excuteA();
}
}
};
}
private static Runnable getThreadB(final Service service) {
return new Runnable() {
@Override
public void run() {
for (;;) {
service.excuteB();
}
}
};
}
private static Runnable getThreadC(final Service service) {
return new Runnable() {
@Override
public void run() {
for (;;) {
service.excuteC();
}
}
};
}
public static void main(String[] args) {
Service service = new Service();
Runnable A = getThreadA(service);
Runnable B = getThreadB(service);
Runnable C = getThreadC(service);
new Thread(B, "B").start();
new Thread(A, "A").start();
new Thread(C, "C").start();
}
}
运行启动类,查看控制台输出结果:
图片.pngA,B,C三个线程一直按照顺序执行。