package com.test;
import java.util.ArrayList;
public class Lock {
private static volatile int xFlag = 0;
private static volatile Lock xLock = new Lock();
private static volatile int topPrio = -1;
private static volatile ArrayList waitingThreads = new ArrayList();
public static void lock() {
synchronized (xLock) {
while (true) {
if (xFlag == 0 && waitingThreads.isEmpty()) {
xFlag = 1;
return;
} else if (xFlag == 0 && !waitingThreads.isEmpty()) {
for (Thread t : waitingThreads) {
if (t.getPriority() > topPrio)
topPrio = t.getPriority();
}
if (Thread.currentThread().getPriority() >= topPrio) {
xFlag = 1;
waitingThreads.clear();// reset waitingThreads
topPrio = -1; // reset topPrio
xLock.notifyAll();
return;
}
try {
xLock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
} else {
try {
waitingThreads.add(Thread.currentThread());
xLock.wait();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
}
}
public static void unlock() {
synchronized (xLock) {
xFlag = 0;
xLock.notifyAll();
}
}
}
1.289406
103.849961
Published