14.显式的锁机制,显式的等待唤醒机制--lock和condition

Lock比synchronized更广泛,更复杂的锁操作


condition对象:

await(),signal(),signalAll()等等


----------------------------------

建立锁对象: Lock lock=new ReentrantLock();

建立Condition对象:Condition condition=lock.newCondition();


修改上一节代码示例:


package 线程通信;


import java.security.interfaces.RSAKey;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;


import 电话号码.Main;


public class Resourse{
private String name;
private int count=1;
private boolean flag=false;
private Lock lock=new ReentrantLock();

private Condition condition=lock.newCondition();


/*************flag_1() flag_2()为唤醒线程方法,flag_3() flag_4()为等待线程方法******/

public void flag_1(String name){
lock.lock();
try {
this.name=name+"--"+count++;
System.out.println(Thread.currentThread().getName()+"生产者..."+this.name);
flag=true;
condition.signalAll();
} finally {
lock.unlock();
// TODO: handle finally clause
}
}
public void flag_2(){
lock.lock();
try {
System.out.println(Thread.currentThread().getName()+"..."+this.name);
flag=false;
condition.signalAll();
} finally {
lock.unlock();
// TODO: handle finally clause
}
}
public void flag_3() throws InterruptedException{
lock.lock();
try {
if(flag==true)condition.await();
} finally {
lock.unlock();
// TODO: handle finally clause
}
}
public void flag_4() throws InterruptedException{
lock.lock();
try {
if(flag==false)condition.await();
} finally {
lock.unlock();
// TODO: handle finally clause
}
}




public static void main(String[] args) {
Resourse resourse=new Resourse();
Producer producer=new Producer(resourse);
Consumer consumer=new Consumer(resourse);
Thread t1=new Thread(producer);
Thread t2=new Thread(consumer);
t1.start();
t2.start();
}


}
class Producer  implements Runnable{
private Resourse resourse;
Producer(Resourse resourse){
this.resourse=resourse;
}
public void run(){
try{
while(true){
resourse.flag_3();

resourse.flag_1("+商品+");

}
}catch (InterruptedException e) {
// TODO: handle exception
}

}
}
class Consumer implements Runnable{
private Resourse resourse;
Consumer(Resourse resourse){
this.resourse=resourse;
}
public void run(){
try{
while(true){
resourse.flag_4();

resourse.flag_2();

}
}catch (InterruptedException e) {
// TODO: handle exception
}

}
}


-----------------

总结:

每个对lock()的调用都必须紧跟一个try-finally,保证在所有情况下都可以释放锁

任务在可以调用await() signal() signalAll之前必须拥有这个锁。


由代码可以看出,Lock锁机制比较复杂,所以经常使用于更加复杂的多线程问题上。









评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值