SHARE
TWEET

Untitled

a guest Jan 15th, 2020 71 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. import java.util.concurrent.Semaphore;
  2.  
  3. class IntCell {
  4.     private int n = 0;
  5.     public int getN() {return n;}
  6.     public void setN(int n) {this.n = n;}
  7. }
  8.  
  9. class Count extends Thread {
  10.     static IntCell n = new IntCell();
  11.     static Semaphore s = new Semaphore(1);
  12.     @Override public void run() {
  13.       int temp;
  14.       for (int i = 0; i < 200000; i++) {
  15.         try {
  16.             s.acquire();
  17.         } catch (InterruptedException e) {
  18.             e.printStackTrace();}
  19.         temp = n.getN();
  20.         n.setN(temp + 1);
  21.        
  22.         s.release();
  23.       }
  24.     }
  25.  
  26.     public static void main(String[] args) {
  27.       Count p = new Count();
  28.       Count q = new Count();
  29.       p.start();
  30.       q.start();
  31.       try { p.join(); q.join(); }
  32.       catch (InterruptedException e) { }
  33.       System.out.println("The value of n is " + n.getN());
  34.     }
  35. }
  36.  
  37. class IntCell {
  38.     private int n = 0;
  39.     private boolean done=true;
  40.    
  41.     public synchronized int getN()
  42.     {
  43.         try {
  44.             while(!done)
  45.                 wait();
  46.            
  47.         }catch(InterruptedException e) {}
  48.         done=false;
  49.         notifyAll();
  50.         return n;
  51.     }
  52.     public synchronized void setN(int n) {
  53.         try {
  54.             while(done)
  55.                 wait();
  56.         }catch(InterruptedException e) {}
  57.         done=true;
  58.         notifyAll();
  59.         this.n = n;
  60.     }
  61. }
  62.  
  63. class Count extends Thread {
  64.     static IntCell n = new IntCell();
  65.     @Override public void run() {
  66.       int temp;
  67.       for (int i = 0; i < 200000; i++) {
  68.         temp = n.getN();
  69.         n.setN(temp + 1);
  70.       }
  71.     }
  72.  
  73.     public static void main(String[] args) {
  74.       Count p = new Count();
  75.       Count q = new Count();
  76.       Count w = new Count();
  77.       p.start();
  78.       q.start();
  79.       w.start();
  80.       try { p.join(); q.join(); w.join(); }
  81.       catch (InterruptedException e) { }
  82.       System.out.println("The value of n is " + n.getN());
  83.     }
  84. }
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
 
Top