多线程——互斥锁

同步加锁

使用ReentrantLock类的lock和unlock方法进行同步通信
使用ReentrantLock类的newCondition方法可以获取Condition对象,需要等待的时候使用Conditionde await方法,唤醒的时候用signal方法,不同的线程使用不同的Condition,这样就能区分唤醒的时候找那个线程了

public static void main(String[] args){
//创建线程任务
MyTask task=new MyTask();
//开启两个线程执行两个任务
new Thread(){
public void run(){
while(true){
try{
task.task1();
}catch(InterruptedException e){
e.printStackTrace();
}
try{
Thread.sleep(10);
}catch(InterruptedException e){
e.printStackTrace();
}
}
};
}.start();

new Thread(){
public void run(){
while(true){
try{
task.task2();
}catch(InterruptedException e){
e.printStackTrace();
}
try{
Thread.sleep(10);
}catch(InterruptedException e){
e.printStackTrace();
}
}
};
}.start();
}

class MyTask(){
//创建互斥锁对象
ReentrantLock r1=new ReentrantLock();
//创建3个Condition
Condition c1=r1.newCondition();
Condition c2=r1.newCondition();
Condition c3=r1.newCondition();
//标识,1可以执行任务1,2可以执行任务2,3可以执行任务3
int flag=1;
public void task1() throws InterruptedException{
r1.lock();//加锁
if(flag!=1){
c1.await();//当前线程等待
}
System.out.println(“1.银行信用卡自动还款业务…”);
flag=2;
//指定唤醒线程2
c2.signal();
r1.unlock();//解锁
}
public synchronized void task2() throws InterruptedException{
r1.lock();
if(flag!=2){
c2.await();//当前线程等待
}
System.out.println(“2.银行储蓄卡自动还款业务…”);
flag=3;
c3.signal();//唤醒线程3
r1.unlock();
}
public synchronized void task3() throws InterruptedException{
r1.lock();
if(flag!=3){
c3.await();//当前线程等待
}
System.out.println(“1.银行短信提醒业务…”);
flag=1;
c1.signal;//唤醒线程1
r1.unlock();
}
}

发布了89 篇原创文章 · 获赞 0 · 访问量 1547

猜你喜欢

转载自blog.csdn.net/ShiZaolin/article/details/104249413
今日推荐