进行同步操作一般使用synchronized, 如果不使用synchronized, 只使用下面的这个Lock类如何进行同步呢?我还没有想出使用它的例子。谢谢。public class Lock {
private static class Waiter {
Thread t;
Waiter() {
t = Thread.currentThread();
}
} private boolean locked = false;
private List<Waiter> waiters = new ArrayList<Waiter>();
//aquire a lock.
//will block if the lock not available.
//return recursion depth (always 1 for non-recursive locks)
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;
}
//Attempts to acquire a lock immediately.
public synchronized int acquire_try() {
if (locked) return 0;
locked = true;
return 1;
}}
private static class Waiter {
Thread t;
Waiter() {
t = Thread.currentThread();
}
} private boolean locked = false;
private List<Waiter> waiters = new ArrayList<Waiter>();
//aquire a lock.
//will block if the lock not available.
//return recursion depth (always 1 for non-recursive locks)
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;
}
//Attempts to acquire a lock immediately.
public synchronized int acquire_try() {
if (locked) return 0;
locked = true;
return 1;
}}
是想用于嵌套事务么?
acquire 返回递归深度,int
release 返回剩下的递归深度 int
acquire_try 尽力获得lock 返回int
这三个方法。