`

学会显示地使用Lock

阅读更多
Lock对象在使用的时候必须被显示地创建、锁定和释放。它和synchronized关键字的作用类似,举一个例子如下:

======================整数生成类
public abstract class IntGenerator {

private volatile boolean canceled=false;

public abstract int next();

public void cancel()
{   this.canceled=false;
}

public boolean isCanceled()
{
return this.canceled;
}


}

===========================实现类
public class MutexEvenGenerator extends IntGenerator{
   private int currentEvenValue=0;
   private java.util.concurrent.locks.Lock lock=new ReentrantLock();

@Override
public int next() {
// TODO Auto-generated method stub
try {
lock.lock();
++currentEvenValue;
Thread.yield();
++currentEvenValue;
return currentEvenValue;
}finally{

lock.unlock();
}
}


public static void main(String[] args){

EvenChecker.test(new MutexEvenGenerator(),10);
}
}


================================
public class EvenChecker implements Runnable{
private IntGenerator generator;
private final int id;

public EvenChecker(IntGenerator generator,int id) {
// TODO Auto-generated constructor stub
this.generator=generator;
this.id=id;
}

@Override
public void run() {
// TODO Auto-generated method stub
while(!generator.isCanceled())
{
int val=generator.next();
if(val%2!=0)
{
System.out.println(val+ " is not even!");
generator.cancel();
}
else
{
//System.out.println(val+" is even!");
}
}

}



public static void test(IntGenerator gp,int count)
{

System.out.println("Press Ctrl+C to Exit");
ExecutorService exec=Executors.newCachedThreadPool();
for(int i=0;i<count;i++)
exec.execute(new EvenChecker(gp,i));
}


public static void test(IntGenerator gp)
{
test(gp,10);
}




}
分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics