Advertisement
Josif_tepe

Untitled

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