Java:
public class TestL{
private boolean isLocked = false;
private Thread lockingThread = null;
private List<Object> waitingThreads = new ArrayList<>();
public void lock() throws InterruptedException {
Object queueObject = new Object();
synchronized (this) {
waitingThreads.add(queueObject);
while (isLocked || waitingThreads.get(0) != queueObject) {
synchronized (queueObject) {
try {
queueObject.wait();
} catch (InterruptedException e) {
waitingThreads.remove(queueObject);
throw e;
}
}
}
waitingThreads.remove(queueObject);
isLocked = true;
lockingThread = Thread.currentThread();
}
}
public synchronized void unlock() {
if (this.lockingThread != Thread.currentThread()) {
throw new IllegalMonitorStateException("Calling thread has not locked this lock");
}
isLocked = false;
lockingThread = null;
if (waitingThreads.size() > 0) {
Object queueObject = waitingThreads.get(0);
synchronized (queueObject) {
queueObject.notifyAll();
}
}
}
public void zähler() throws InterruptedException {
lock();
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread().getName() + " : " + i);
}
unlock();
}
}
class Main {
public static void main(String[] args) throws InterruptedException {
TestL lock = new TestL();
Thread[] threads = new Thread[5];
for (int i = 0; i < 5; i++) {
threads[i] = new TestThread(fairLock);
threads[i].start();
}
}
}
class TestThread extends Thread {
TestL lock;
public TestThread(TestL lock) {
this.lock = lock;
}
@Override
public void run() {
try {
lock.count();
} catch (InterruptedException exception) {
exception.printStackTrace();
}
}
}