Advertisement
Guest User

Untitled

a guest
Oct 14th, 2019
110
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.76 KB | None | 0 0
  1. class Counter {
  2.     private int _val;
  3.  
  4.     public Counter(int n) {
  5.         _val = n;
  6.     }
  7.  
  8.     public void inc() {
  9.         _val++;
  10.     }
  11.  
  12.     public void dec() {
  13.         _val--;
  14.     }
  15.  
  16.     public int value() {
  17.         return _val;
  18.     }
  19. }
  20.  
  21. class Mutex {
  22.     public int whosTurn = 0;
  23.     public boolean[] interested = {false, false};
  24. }
  25.  
  26. class IThread extends Thread {
  27.     private Counter cnt;
  28.     private Mutex mutex;
  29.  
  30.  
  31.     public IThread(Counter cnt, Mutex mutex) {
  32.         this.cnt = cnt;
  33.         this.mutex = mutex;
  34.     }
  35.  
  36.     public void run() {
  37.         for (int i = 0; i < 10000; i++) {
  38.             mutex.interested[0] = true;
  39.             mutex.whosTurn = 1;
  40.             while (mutex.interested[1] && mutex.whosTurn == 1) {}
  41.  
  42.             cnt.inc();
  43.             mutex.interested[0] = false;
  44.         }
  45.     }
  46. }
  47.  
  48. class DThread extends Thread {
  49.     private Counter cnt;
  50.     private Mutex mutex;
  51.  
  52.     public DThread(Counter cnt, Mutex mutex) {
  53.         this.cnt = cnt;
  54.         this.mutex = mutex;
  55.     }
  56.  
  57.     public void run() {
  58.         for (int i = 0; i < 10000; i++) {
  59.             mutex.interested[1] = true;
  60.             mutex.whosTurn = 0;
  61.             while (mutex.interested[0] && mutex.whosTurn == 0) {}
  62.  
  63.             cnt.dec();
  64.             mutex.interested[1] = false;
  65.         }
  66.     }
  67. }
  68.  
  69. public class Race {
  70.     public static void main(String[] args) throws InterruptedException {
  71.         Counter cnt = new Counter(0);
  72.         Mutex mutex = new Mutex();
  73.  
  74.         Thread iThread = new IThread(cnt, mutex);
  75.         Thread dThread = new DThread(cnt, mutex);
  76.  
  77.         iThread.start();
  78.         dThread.start();
  79.  
  80.         iThread.join();
  81.         dThread.join();
  82.  
  83.         System.out.println("stan=" + cnt.value());
  84.     }
  85. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement