understanding synchronized in java

て烟熏妆下的殇ゞ 提交于 2020-01-17 07:48:03

问题


Why usually threading samples put so many code in synchronized block. According to my understanding in following case synchronized is used just for locking b for wait and notify:

Main class ThreadA :

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 class ThreadB:

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 just wait and notify in synchronized block:

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());


     }
  }

回答1:


According to my understanding in following case synchronized is used just for locking b for wait and notify

Your understanding is wrong.

synchronized is also used for:

  • Mutual exclusion, to ensure that only one thread executes code "guarded" by a particular monitor at a time
  • Ensuring memory access across threads is correct (that one thread sees changes made by another thread)

What will change if I put just wait and notify in synchronized block:

In this particular case, it will make a difference based on a race condition - in the original code, if the new thread starts executing before the synchronized block is reached in the original thread, it won't get as far as "Waiting for b to complete" until the second thread has finished... at which point it will block forever in wait.

Note that it's a really bad idea to wait on Thread monitors, as wait/notify is used internally by Thread.

In short, the example you've used is a bad one to start with in various ways - but synchronization is used for more than just wait/notify.




回答2:


Please note that total += i is not an atomic operation in Java. So you have to sync also this construct.

You also have not to sync notify() and wait() because their locks are handled internally.



来源:https://stackoverflow.com/questions/17965751/understanding-synchronized-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!