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锁机制比较复杂,所以经常使用于更加复杂的多线程问题上。