Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.concurrent.Semaphore;
- class IntCell {
- private int n = 0;
- public int getN() {return n;}
- public void setN(int n) {this.n = n;}
- }
- class Count extends Thread {
- static IntCell n = new IntCell();
- static Semaphore s = new Semaphore(1);
- @Override public void run() {
- int temp;
- for (int i = 0; i < 200000; i++) {
- try {
- s.acquire();
- } catch (InterruptedException e) {
- e.printStackTrace();}
- temp = n.getN();
- n.setN(temp + 1);
- s.release();
- }
- }
- public static void main(String[] args) {
- Count p = new Count();
- Count q = new Count();
- p.start();
- q.start();
- try { p.join(); q.join(); }
- catch (InterruptedException e) { }
- System.out.println("The value of n is " + n.getN());
- }
- }
- class IntCell {
- private int n = 0;
- private boolean done=true;
- public synchronized int getN()
- {
- try {
- while(!done)
- wait();
- }catch(InterruptedException e) {}
- done=false;
- notifyAll();
- return n;
- }
- public synchronized void setN(int n) {
- try {
- while(done)
- wait();
- }catch(InterruptedException e) {}
- done=true;
- notifyAll();
- this.n = n;
- }
- }
- class Count extends Thread {
- static IntCell n = new IntCell();
- @Override public void run() {
- int temp;
- for (int i = 0; i < 200000; i++) {
- temp = n.getN();
- n.setN(temp + 1);
- }
- }
- public static void main(String[] args) {
- Count p = new Count();
- Count q = new Count();
- Count w = new Count();
- p.start();
- q.start();
- w.start();
- try { p.join(); q.join(); w.join(); }
- catch (InterruptedException e) { }
- System.out.println("The value of n is " + n.getN());
- }
- }
RAW Paste Data