Advertisement
Josif_tepe

Untitled

Mar 24th, 2022
678
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.41 KB | None | 0 0
  1. import java.util.concurrent.Semaphore;
  2. import java.util.concurrent.locks.Lock;
  3. import java.util.concurrent.locks.ReentrantLock;
  4.  
  5. public class Main {
  6.     public static void main(String[] args) {
  7.         Brojac brojac = new Brojac();
  8.     Brojac brojac2 = new Brojac();
  9.         t t1 = new t(1, brojac);
  10.         t t2 = new t(2, brojac2);
  11.     t1.start();
  12.     t2.start();
  13.     try {
  14.         t1.join();
  15.         t2.join();
  16.     }
  17.     catch (InterruptedException ex) {
  18.         ex.printStackTrace();
  19.     }
  20.         System.out.println(brojac.getCnt());
  21.         System.out.println(brojac2.getCnt());
  22.  
  23.  
  24.  }
  25. }
  26. class t extends  Thread {
  27.     int id;
  28.     static Brojac br;
  29.     public t(int _id, Brojac br) {
  30.         id = _id;
  31.         this.br = br;
  32.     }
  33.  
  34.     @Override
  35.     public void run() {
  36.       for(int i = 0; i < 20; i++) {
  37.           try {
  38.               br.zgolemi_brojac_semaphore();
  39.           }
  40.           catch (Exception ex) {
  41.  
  42.           }
  43.       }
  44.     }
  45. }
  46. class Brojac  {
  47.     private static int cnt = 0;
  48.     private static Semaphore semaphore = new Semaphore(2);
  49. //    public static void zgolemi_brojac() {
  50. //        cnt++;
  51. //    }
  52.     public void zgolemi_brojac_semaphore() {
  53.         try {
  54.             semaphore.acquire();
  55.             cnt++;
  56.             semaphore.release();
  57.         }
  58.         catch (Exception e) {
  59.  
  60.         }
  61.     }
  62.     public static int getCnt() {
  63.         return cnt;
  64.     }
  65. }
  66.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement