CCCPaste

Untitled

import java.util.concurrent.Semaphore;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class Main {
    public static void main(String[] args) {
        Brojac brojac = new Brojac();
    Brojac brojac2 = new Brojac();
        t t1 = new t(1, brojac);
        t t2 = new t(2, brojac2);
    t1.start();
    t2.start();
    try {
        t1.join();
        t2.join();
    }
    catch (InterruptedException ex) {
        ex.printStackTrace();
    }
        System.out.println(brojac.getCnt());
        System.out.println(brojac2.getCnt());


 }
}
class t extends  Thread {
    int id;
    static Brojac br;
    public t(int _id, Brojac br) {
        id = _id;
        this.br = br;
    }

    @Override
    public void run() {
      for(int i = 0; i < 20; i++) {
          try {
              br.zgolemi_brojac_semaphore();
          }
          catch (Exception ex) {

          }
      }
    }
}
class Brojac  {
    private static int cnt = 0;
    private static Semaphore semaphore = new Semaphore(2);
//    public static void zgolemi_brojac() {
//        cnt++;
//    }
    public void zgolemi_brojac_semaphore() {
        try {
            semaphore.acquire();
            cnt++;
            semaphore.release();
        }
        catch (Exception e) {

        }
    }
    public static int getCnt() {
        return cnt;
    }
}