Understanding synchronized in java

Why is it that usually streaming samples put so much code in a synchronized block. According to my understanding, in the following case, synchronized is used only to lock b for waiting and notification:

Core ThreadA class:

class ThreadA {
      public static void main(String [] args) {
         ThreadB b = new ThreadB();
         b.start();

         synchronized(b) {
            try {
               System.out.println("Waiting for b to complete...");

              b.wait();
           } catch (InterruptedException e) {}
           System.out.println("Total is: " + b.total);
           System.out.println(Thread.currentThread().getName());

        }
     }
  }

and ThreadB class:

class ThreadB extends Thread {   
     int total;     
     public void run() {
        synchronized(this) 
        {
           System.out.println();
           for(int i=0;i<100;i++) 
           {
               System.out.println(Thread.currentThread().getName());
              total += i;
           }
           notify();
        }
     }
  }

What will change if I put only waitand notifyto synchronized:

class ThreadA {
      public static void main(String [] args) {
         ThreadB b = new ThreadB();
         b.start();
            try {
               System.out.println("Waiting for b to complete...");

                synchronized(b) {   b.wait();}
           } catch (InterruptedException e) {}
           System.out.println("Total is: " + b.total);
           System.out.println(Thread.currentThread().getName());


     }
  }
0
source share
2 answers

According to my understanding, in the following case, synchronized is used only to lock b for waiting and notification

Your understanding is wrong.

synchronized also used for:

  • , , , ""
  • ( , )

, :

- , thread , , " b ", ... wait.

, thread, wait/notify thread.

, , , , , wait/notify.

+4

, total += i - Java. .

() (), .

0

Source: https://habr.com/ru/post/1766465/


All Articles