ReentrantLock介绍
- 使用ReentrantLock类也可以实现同步加锁
- ReentrantLock叫[互斥锁],使用lock()和unlock()方法进行同步
- 使用ReentrantLock类的newCondition()方法可以获取Condition对象
- 需要等待的时候使用Condition的await()方法, 唤醒的时候用signal()方法
- 不同的线程使用不同的Condition, 这样就能区分唤醒的时候找哪个线程了
使用ReentrantLock类使用要点
- 使用ReentrantLock类的newCondition()方法可以获取Condition对象
- 需要等待的时候使用Condition的await()方法, 唤醒的时候用signal()方法
- 不同的线程使用不同的Condition, 这样就能区分唤醒的时候找哪个线程了
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class ReentrantLockDemo {
public static void main(String[] args) {
MyTaskThree task = new MyTaskThree();
new Thread(() -> {
while(true){
try {
task.task1();//执行任务1
} catch (InterruptedException e) {
e.printStackTrace();
}
try{
Thread.sleep(10);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}).start();
new Thread(){
@Override
public void run() {
while(true){
try {
task.task2();//执行任务2
} catch (InterruptedException e) {
e.printStackTrace();
}
try{
Thread.sleep(10);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}.start();
new Thread(){
@Override
public void run() {
while(true){
try {
task.task3();//执行任务3
} catch (InterruptedException e) {
e.printStackTrace();
}
try{
Thread.sleep(10);
}catch(InterruptedException e){
e.printStackTrace();
}
}
}
}.start();
}
}
/*
/**
* 互斥锁的使用步骤
* 1.创建互斥锁对象
* 2.创建3个Condition
* 3.加锁、解锁
* 4.线程等待-Condition的await方法
* 5.线程唤醒-Condition的signal方法
* @author tuba
*
*/
class MyTasks{
ReentrantLock r = new ReentrantLock();
Condition c1 = r.newCondition();
Condition c2 = r.newCondition();
Condition c3 = r.newCondition();
int flag = 1;//标识 1:可以执行任务1,2:可以执行任务2
public void task1() throws InterruptedException {
r.lock();
if(flag != 1){
c1.wait();//当前线程等待 ,抛出中断异常
}
System.out.println("1.银行信用卡自动还款任务...");
this.flag = 2;
c2.signal();//唤醒指定线程2
r.unlock();
}
public void task2() throws InterruptedException {
r.lock();
if(flag != 2){
c2.wait();//当前线程等待 ,抛出中断异常
}
System.out.println("2.银行储蓄卡自动结算利息任务...");
this.flag = 3;
c3.signal();//唤醒指定线程3
r.unlock();
}
public void task3() throws InterruptedException {
r.lock();
if(flag != 3){
c3.wait();//当前线程等待 ,抛出中断异常
}
System.out.println("3.银行短信提醒任务...");
this.flag = 1;
c1.signal();//唤醒指定线程3
r.unlock();
}
}