example code to show how java synchronized block works

CaiNiaoCoder picture CaiNiaoCoder · Nov 17, 2011 · Viewed 58.7k times · Source

I am learning java multi-threading, I found it's hard to understand how synchronized block works:

 synchronized(Object o){
     // do something
    }

please give some example code that can show me the Object o is blocked. As how I understand this, accessing object o from another thread will be blocked while the synchronized block is being excuted?

Answer

Lucifer picture Lucifer · Nov 17, 2011

Synchronization in Java is an important concept since Java is a multi-threaded language where multiple threads run in parallel to complete program execution. In multi-threaded environment synchronization of java object or synchronization of java class becomes extremely important. Synchronization in Java is possible by using java keyword "synchronized" and "volatile”. Concurrent access of shared objects in Java introduces to kind of errors: thread interference and memory consistency errors and to avoid these errors you need to properly synchronize your java object to allow mutual exclusive access of critical section to two threads.

Read more: http://javarevisited.blogspot.com/2011/04/synchronization-in-java-synchronized.html#ixzz2LOWwnCjH

Please Look at this Example