设为首页 加入收藏

TOP

用悲观锁原理来实现乐观锁的接口
2014-11-24 00:10:26 来源: 作者: 【 】 浏览:4
Tags:悲观 原理 实现 乐观 接口

import java.util.Date;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.Lock;


/**
*
*/
public class SimpleLock implements Lock {
private boolean locked;


@Override
public void lock() {
boolean intr = Thread.interrupted();
synchronized(this){
while(locked){
try {
wait();
} catch (InterruptedException e) {
intr = true;
}
}
locked = true;
}
if(intr) Thread.currentThread().interrupt();
}


@Override
public void lockInterruptibly() throws InterruptedException {
synchronized(this){
while(locked){
wait();
}
locked = true;
}
}


@Override
public boolean tryLock() {
if(locked){
return false;
} else {
locked = true;
return true;
}
}


private static long clipHigh(long value){
return value < 0 Long.MAX_VALUE : value;
}
@Override
public boolean tryLock(long time, TimeUnit unit)
throws InterruptedException {
if(time < 0){
return false;
}
synchronized(this){
long now = System.currentTimeMillis();
long deadline = clipHigh(now + unit.toMillis(time));
synchronized(this){
if(!locked){
return locked = true;
}
for(;;){
long remaining = deadline – now;
if(remaining <= 0){
return false;
}
wait(remaining);
if(!locked){
return locked = true;
}
now = System.currentTimeMillis();
}
}
}
}


@Override
public void unlock() {
synchronized(this){
locked = false;
}
}


@Override
public Condition newCondition() {
return new SimpleCondition();
}


class SimpleCondition implements Condition {


@Override
public void await() throws InterruptedException {
synchronized(this){
unlock();
try{
wait();
} finally {
lock();
}
}
}


@Override
public void awaitUninterruptibly() {
boolean intr = Thread.interrupted();
synchronized(this){
unlock();
try {
wait();
} catch (InterruptedException e) {
intr = true;
} finally {
lock();
}
if(intr)
Thread.currentThread().interrupt();
}
}


@Override
public long awaitNanos(long nanosTimeout) throws InterruptedException {
unlock();
try{
final long start = System.nanoTime();
synchronized(this){
wait(nanosTimeout / 1000000L, (int) (nanosTimeout % 1000000L));
}
return nanosTimeout – (System.nanoTime() – start);
} finally {
lock();
}
}


@Override
public boolean await(long time, TimeUnit unit)
throws InterruptedException {
throw new UnsupportedOperationException();
}


@Override
public boolean awaitUntil(Date deadline) throws InterruptedException {
throw new UnsupportedOperationException();
}


@Override
public void signal() {
synchronized(this){
notify();
}
}


@Override
public void signalAll() {
synchronized(this){
notifyAll();
}
}


}


}


】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇中软国际2012校园招聘 下一篇英语面试中经常遇到的英语单词

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容: