Created
March 1, 2017 15:28
-
-
Save rctl/02d5d0ccffaf08b0fc983a7641a11436 to your computer and use it in GitHub Desktop.
Simple monitor test written in Java
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.util.*; | |
class Monitor{ | |
private static class SimpleMonitor{ | |
private static class ConditionVariable{ | |
boolean lock; | |
public ConditionVariable(boolean lock){ | |
this.lock = lock; | |
} | |
public void signal(){ | |
this.lock = false; | |
} | |
public void hold(){ | |
try { | |
while(this.lock){ Thread.sleep(5); }; | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
} | |
Queue<ConditionVariable> q = new LinkedList<ConditionVariable>(); | |
ConditionVariable qlock = new ConditionVariable(false); | |
public void acquire(){ | |
try { | |
qlock.hold(); | |
ConditionVariable c = new ConditionVariable(!q.isEmpty()); | |
q.add(c); | |
qlock.signal(); | |
c.hold(); | |
}catch(Exception e){ | |
e.printStackTrace(); | |
} | |
} | |
public void release(){ | |
qlock.hold(); | |
q.poll(); | |
if(!q.isEmpty()){ | |
q.peek().signal(); | |
} | |
qlock.signal(); | |
} | |
} | |
public static int counter = 0; | |
public static void main(String[] args) { | |
final SimpleMonitor monitor = new SimpleMonitor(); | |
for(int i = 0; i < 4; i++){ | |
new Thread(new Runnable() { | |
@Override | |
public void run() { | |
try { | |
while(true){ | |
monitor.acquire(); | |
System.out.println("Working..."); | |
counter++; | |
Thread.sleep(5 + (int)(Math.random() * 10)); | |
if (counter > 1){ | |
System.out.println("Oh No! THERE WAS A COLLISION IN THE CRITICAL SECTION!!!!!!!"); | |
} | |
counter--; | |
monitor.release(); | |
} | |
} catch (Exception e) { | |
e.printStackTrace(); | |
} | |
} | |
}).start(); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment