Advertisement
Josif_tepe

Untitled

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