这个类Lock实现了先进先出的同步,即最先被block的线程首先被unblock.怎么用这个类实现递归lock? 即如果一个线程获得了一个对象的lock,该线程可以继续获得此对象的lock而不被block,下面的这个先进先出lock不能做到这一点(用Test类测试),只有线释放了lock之后,此线程才可以继续得到lock. 要求用下面的先进先出Lock类进行所有的同步操作,不使用java的sinchronized等同步工具(为了确保先进先出的同步特点),实现一个可以递归锁的类。递归锁和先进先出Lock类有一样同名的3个方法。1.int acquire()
获得锁.
如果没有可用的锁将block.
返回递归深度 2. int release()
释放锁,返回剩下的递归深度 3.
boolean tryacquire()
尽力获得锁
返回boolean//测试
Public class Test{
static Lock lock = new Lock();public static void main(final String[] args){
func1();
}
static void func1(){
lock.aqcuire();
System.out.println();
func2();//blocked here 当前线程已经获得了所,所以它不能再获得其它的锁,必须等释放锁后才能获得其它的锁
lock.release();
}static void func2(){
lock.aqcuire();
System.out.println("cannot be printed by func1");
lock.release();
}}//先进先出锁
public class Lock {
private static class Waiter {
Thread t;
Waiter() {
t = Thread.currentThread();
}
} private boolean locked = false; private List <Waiter> waiters = new ArrayList <Waiter> (); public int acquire() {
Waiter w = new Waiter();
boolean must_wait;
synchronized (w) {
synchronized (this) {
if (locked) {
must_wait = true;
waiters.add(w);
} else {
must_wait = false;
locked = true;
}
}
if (must_wait) {
try {
w.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
return 1;
}
//Releases a lock
public synchronized int release() {
int wait_count = waiters.size();
if (wait_count == 0) {
locked = false;
} else {
Waiter w = waiters.remove(0);
synchronized (w) {
w.notify();
}
}
return 0;
}
public synchronized int tryacquire() {
if (locked) return 0;
locked = true;
return 1;
} }
获得锁.
如果没有可用的锁将block.
返回递归深度 2. int release()
释放锁,返回剩下的递归深度 3.
boolean tryacquire()
尽力获得锁
返回boolean//测试
Public class Test{
static Lock lock = new Lock();public static void main(final String[] args){
func1();
}
static void func1(){
lock.aqcuire();
System.out.println();
func2();//blocked here 当前线程已经获得了所,所以它不能再获得其它的锁,必须等释放锁后才能获得其它的锁
lock.release();
}static void func2(){
lock.aqcuire();
System.out.println("cannot be printed by func1");
lock.release();
}}//先进先出锁
public class Lock {
private static class Waiter {
Thread t;
Waiter() {
t = Thread.currentThread();
}
} private boolean locked = false; private List <Waiter> waiters = new ArrayList <Waiter> (); public int acquire() {
Waiter w = new Waiter();
boolean must_wait;
synchronized (w) {
synchronized (this) {
if (locked) {
must_wait = true;
waiters.add(w);
} else {
must_wait = false;
locked = true;
}
}
if (must_wait) {
try {
w.wait();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
return 1;
}
//Releases a lock
public synchronized int release() {
int wait_count = waiters.size();
if (wait_count == 0) {
locked = false;
} else {
Waiter w = waiters.remove(0);
synchronized (w) {
w.notify();
}
}
return 0;
}
public synchronized int tryacquire() {
if (locked) return 0;
locked = true;
return 1;
} }
解决方案 »
免费领取超大流量手机卡,每月29元包185G流量+100分钟通话, 中国电信官方发货