Advertisement
Josif_tepe

Untitled

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