Advertisement
Josif_tepe

Untitled

Mar 31st, 2021
119
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.77 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 b = new Brojac();
  7.         Brojac b2 = new Brojac();
  8.         MyThread t1 = new MyThread(1, b);
  9.         MyThread t2 = new MyThread(2, b2);
  10.         t1.start();
  11.         t2.start();
  12.         try {
  13.             t1.join();
  14.             t2.join();
  15.         }
  16.         catch (InterruptedException ie) {
  17.             System.out.println(ie);
  18.         }
  19.        System.out.println(b.getBr());
  20.         System.out.println(b2.getBr());
  21.  
  22.     }
  23. }
  24.  
  25. class MyThread extends Thread {
  26.     private int id;
  27.  
  28.     Brojac b;
  29.     public MyThread(int _id, Brojac _b) {
  30.         id = _id;
  31.         b = _b;
  32.     }
  33.  
  34.     @Override
  35.     public void run() {
  36.         for(int i = 0; i < 10; ++i) {
  37. //            System.out.println("Thread " + id + " " + i);
  38.             b.zgolemi_brojac_mutex();
  39.             // zemi ja vrednosta na b
  40.             // zgolemi ja vrednosta T1, T2
  41.             // vrati ja vrednost
  42.         }
  43.     }
  44. }
  45.  
  46. class Brojac {
  47.     private static int br = 0;
  48.     private static Lock lock = new ReentrantLock();
  49.     public static void unsafe_zgolemi_brojac() {
  50.         br++; // no atomicity
  51.         try {
  52.             Thread.sleep(10);
  53.         }
  54.         catch (InterruptedException ie) {
  55.             System.out.println(ie);
  56.         }
  57.     }
  58.     public synchronized void safe_zgolemi_brojac() {
  59.         br++; // atomocity
  60.     }
  61.     public void safe_zgolemuvanje() {
  62.         synchronized (this) {
  63.             br++;
  64.         }
  65.     }
  66.     public static void zgolemi_brojac_mutex() {
  67.         lock.lock();
  68.         br++;
  69.         lock.unlock();
  70.     }
  71.  
  72.     public static int getBr() {
  73.         return br;
  74.     }
  75.  
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement