Lock使用时,使用try..finally..语句,在finally中Lock.unLock来释放锁,同时可以在处理失败的情况下,在finally语句中做优雅的处理
而synchronized语句则无法优雅的结束,发生异常直接退出了
同时,还可以使用tryLock(int x, TimeUnit timeunit)的方法来限时获取锁,获取失败可以做其他事情
package com.test.concurrent;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;
public class MutexEvenGenerator extends EvenGenerator implements Runnable{
public MutexEvenGenerator(IntGenerator ig){
this.ig=ig;
gtest=new GeneratorTester(ig);
}
IntGenerator ig;
GeneratorTester gtest;
@Override
public void run(){
gtest.test();
}
public static void main(String[] args) {
// TODO Auto-generated method stub
ExecutorService exec=Executors.newCachedThreadPool();
IntGenerator ig=new EvenGenerator();
for(int i=0;i<10;i++){
exec.execute(new MutexEvenGenerator(ig));
}
}
}
interface IntGenerator{
int next();
boolean isCanceled();
void cancel();
}
class EvenGenerator implements IntGenerator{
int num=0;
boolean canceled=false;
Lock lock=new ReentrantLock();
public int next(){
<span style="color:#ff0000;">try{
lock.lock();
num++;
Thread.yield();
num++;
return num;
}finally{
lock.unlock();
}</span>
}
public boolean isCanceled(){
return canceled;
}
public void cancel(){
canceled=true;
}
}
class GeneratorTester{
private IntGenerator ig;
public GeneratorTester(IntGenerator ig){
this.ig=ig;
}
public void test(){
int v;
while(ig.isCanceled()==false){
v=ig.next();
if(v%2!=0){
System.out.println("generate even error value:"+v);
ig.cancel();
return;
}
}
}
}