Advertisement
Josif_tepe

Untitled

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