Lock中实现线程的精确唤醒(使多个线程按指定的顺序执行)
程序员文章站
2022-06-10 20:52:37
...
lock中类似wait和notify的方法:
await和signal/signalAll
原理:lock中使用Condition类做为锁监视器,调用Condition的await()和signal()实现线程的等待和唤醒。
实现代码:
Lock lock=new ReentrantLock();
Condition condition=lock.newCondition();
lock.lock();
try{
while(...){
condition.await();
}
condition.signalAll();
}catch(Exception e){
}finally{
lock.unlock();
}
和wait/notifyAll相比的好处:
能够精准的唤醒指定的线程
多线程按顺序执行的实现:
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class OrderThread {
public static void main(String[]args) {
Order order=new Order();
Thread thread1=new Thread(()->{
for(int i=0;i<10;i++) {
order.print1();
}
},"线程1");
Thread thread2=new Thread(()->{
for(int i=0;i<10;i++) {
order.print2();
}
},"线程2");
Thread thread3=new Thread(()->{
for(int i=0;i<10;i++) {
order.print3();
}
},"线程3");
thread1.start();
thread2.start();
thread3.start();
}
}
class Order{
Lock lock=new ReentrantLock();
Condition condition1=lock.newCondition();
Condition condition2=lock.newCondition();
Condition condition3=lock.newCondition();
int number=1;
public void print1() {
lock.lock();
try {
while(number!=1) {
condition1.await();
}
System.out.println(Thread.currentThread().getName()+"正在执行");
number=2;
condition2.signalAll();
}catch(Exception e) {
}finally {
lock.unlock();
}
}
public void print2() {
lock.lock();
try {
while(number!=2) {
condition2.await();
}
System.out.println(Thread.currentThread().getName()+"正在执行");
number=3;
condition3.signalAll();
}catch(Exception e) {
}finally {
lock.unlock();
}
}
public void print3() {
lock.lock();
try {
while(number!=3) {
condition3.await();
}
System.out.println(Thread.currentThread().getName()+"正在执行");
number=1;
condition1.signalAll();
}catch(Exception e) {
}finally {
lock.unlock();
}
}
}
执行结果:
上一篇: 判断字符串是否在list集合中存在
下一篇: Mutex(测)