版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/u012292754/article/details/89814758
1 ReentrantLock
介绍
- 可以实现同步加锁;
- 使用
lock()
,unlock()
方法同步;
1.2 使用要点
- 使用
ReentrantLock
类的newCondition()
方法可以获取 Condition 对象; - 需要等待的时候使用 Condition 的
await()
方法,唤醒的时候用signal()
方法; - 不同的线程使用不同的 Condition,这样在唤醒的时候就能区分线程了;
2 案例
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;
public class Demo13 {
public static void main(String[] args) {
MyTask1 task = new MyTask1();
new Thread() {
@Override
public void run() {
while (true) {
try {
task.task1();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
new Thread() {
@Override
public void run() {
while (true) {
try {
task.task2();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
new Thread() {
@Override
public void run() {
while (true) {
try {
task.task3();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}.start();
}
}
class MyTask1 {
// 创建互斥锁对象
ReentrantLock rl = new ReentrantLock();
// 创建3个 Condition
Condition c1 = rl.newCondition();
Condition c2 = rl.newCondition();
Condition c3 = rl.newCondition();
int flag = 1; // 1:执行任务1
public void task1() throws InterruptedException {
rl.lock(); // 加锁
if (flag != 1) {
c1.await(); // 当前线程等待
}
System.out.println("1.银行信用卡自动还款任务....");
flag = 2;
// 指定唤醒线程2
c2.signal();
rl.unlock(); // 解锁
}
public void task2() throws InterruptedException {
rl.lock();
if (flag != 2) {
c2.await();
}
System.out.println("2.自动利息结算任务。。。");
flag = 3;
c3.signal();
rl.unlock();
}
public void task3() throws InterruptedException {
rl.lock();
if (flag != 3) {
c3.await();
}
System.out.println("3.短信提醒。。。");
flag = 1;
c1.signal();
rl.unlock();
}
}