Advertisement
Josif_tepe

Untitled

Mar 31st, 2021
114
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.40 KB | None | 0 0
  1.  
  2. public class Main {
  3.     public static void main(String[] args) {
  4.         Brojac b = new Brojac();
  5.         Brojac b2 = new Brojac();
  6.         MyThread t1 = new MyThread(1, b);
  7.         MyThread t2 = new MyThread(2, b2);
  8.         t1.start();
  9.         t2.start();
  10.         try {
  11.             t1.join();
  12.             t2.join();
  13.         }
  14.         catch (InterruptedException ie) {
  15.             System.out.println(ie);
  16.         }
  17.        System.out.println(b.getBr());
  18.         System.out.print(b2.getBr());
  19.     }
  20. }
  21.  
  22. class MyThread extends Thread {
  23.     private int id;
  24.     Brojac b;
  25.     public MyThread(int _id, Brojac _b) {
  26.         id = _id;
  27.         b = _b;
  28.     }
  29.  
  30.     @Override
  31.     public void run() {
  32.         for(int i = 0; i < 10; ++i) {
  33. //            System.out.println("Thread " + id + " " + i);
  34.             b.safe_zgolemi_brojac();
  35.             // zemi ja vrednosta na b
  36.             // zgolemi ja vrednosta T1, T2
  37.             // vrati ja vrednost
  38.         }
  39.     }
  40. }
  41.  
  42. class Brojac {
  43.     private static int br = 0;
  44.  
  45.     public static void unsafe_zgolemi_brojac() {
  46.         br++; // no atomicity
  47.         try {
  48.             Thread.sleep(10);
  49.         }
  50.         catch (InterruptedException ie) {
  51.             System.out.println(ie);
  52.         }
  53.     }
  54.     public synchronized void safe_zgolemi_brojac() {
  55.         br++; // atomocity
  56.     }
  57.  
  58.     public static int getBr() {
  59.         return br;
  60.     }
  61.  
  62. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement