daily pastebin goal
2%
SHARE
TWEET

Untitled

a guest Dec 9th, 2018 50 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import java.lang.reflect.Array;
  2. import java.util.ArrayList;
  3.  
  4. public class DekkerLock extends AbstractFixnumLock {
  5.  
  6.     private volatile int turn = 0;
  7.     private static int threadNumber = 2;
  8.    // private volatile boolean t1 = false
  9.  
  10.     private volatile ArrayList<VolatileBool> wantsToEnter = getFilledList(threadNumber, new VolatileBool(false));
  11.  
  12.     DekkerLock() {
  13.         super(threadNumber);
  14.     }
  15.  
  16.     @Override
  17.     public void lock() {
  18.         int threadId = getId();
  19.         int anotherThreadId = getAnotherThreadId(threadId);
  20.         wantsToEnter.set(threadId, new VolatileBool(true));
  21.         while(wantsToEnter.get(anotherThreadId).getBool()) {
  22.             System.out.println("TYT TRED" + turn + threadId);
  23.             if (turn != threadId) {
  24.                 System.out.println("Thread"  + threadId + " lets " + anotherThreadId + " run");
  25.                 wantsToEnter.set(threadId, new VolatileBool(false));
  26.                 while (turn != threadId) {
  27.                     System.out.println("waiting for turn" + turn + (threadId));
  28.                     // the thread waits for its turn
  29.                 }
  30.                 System.out.println("Thread" + threadId + " turn");
  31.                 wantsToEnter.set(threadId, new VolatileBool(true));
  32.             }
  33.         }
  34.     }
  35.  
  36.     @Override
  37.     public void unlock() {
  38.         int threadId = getId();
  39.         wantsToEnter.set(threadId, new VolatileBool(false));
  40.         turn = getAnotherThreadId(threadId);
  41.     }
  42.  
  43.     private static int getAnotherThreadId(int threadId) {
  44.         return (threadId + 1) % threadNumber;
  45.     }
  46. }
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand