微信

使用微信服务,更方便

职友集>Java面试题 > 用悲观锁原理来实现乐观锁的接口

用悲观锁原理来实现乐观锁的接口

2015-08-12 06:30:02 阅读( 227 )

1791人 收藏本页

标签:Java面试题

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();
}
}

}

}

来自IT公司面试手册

下一篇:java中用单例模式有什么好处

上一篇:java读取xml文档

亲~ 如果您有更好的答案 可在评论区发表您独到的见解。

您想查看更多的信息: 面试题