@@ -6,7 +6,13 @@ class Main {
// Create different mutex
Mutex mutD = new MutexTypeD();
+ Task t0 = new Task("T0", 0, mutD);
Task t1 = new Task("T1", 1, mutD);
+
+ t0.describe();
t1.describe();
+ t0.start();
+ t1.start();
}
@@ -1,3 +1,27 @@
public abstract class Mutex {
+ public static void criticalSection() {
+ try {
+ Thread.sleep((int) (Math.random() * 3000));
+ }
+ catch (InterruptedException e) {
+ // Nothing
+ public static void nonCriticalSection() {
+ // Take ownership
+ public abstract void p(int id);
+ // Release ownership
+ public abstract void v(int id);
@@ -1,7 +1,32 @@
class MutexTypeD extends Mutex {
+ private volatile int turn;
+ private volatile boolean[] flag;
MutexTypeD() {
+ turn = 0;
+ flag = new boolean[2];
+ flag[0] = flag[1] = false;
+ public void p(int id) {
+ int other = 1 - id;
+ flag[id] = true;
+ while (flag[other] == true) {
+ if (turn == other) {
+ flag[id] = false;
+ while (turn == other) Thread.yield();
+ public void v(int id) {
+ turn = 1 - id;
public String toString() {
@@ -14,4 +14,18 @@ class Task extends Thread {
public void describe() {
System.out.println(id + "<" + critical + ">:" + name);
+ public void run() {
+ while (true) {
+ critical.p(id);
+ System.out.println( name + " is CRITICAL!");
+ Mutex.criticalSection();
+ critical.v(id);
+ System.out.println( name + " non critical.");
+ Mutex.nonCriticalSection();