(37) synchronized synchronized block

synchronized keyword: lock between threads, shared data to resolve conflicts between threads.

The use of synchronized keyword:

synchronized ( an arbitrary object (lock) ) {

  Code shared data block in the discharge operation.

}

Multi-modified code is synchronized, if hold the same lock, which pieces of code can not run concurrently.

 

Code examples:

public class MySynchronized {
       public static void main(String[] args) {
              final MySynchronized mySynchronized = new MySynchronized();
              final MySynchronized mySynchronized2 = new MySynchronized();
              new Thread("thread1") {
                      public void run() {
                             synchronized (mySynchronized) {
                      try {
                             System.out.println(this.getName()+" start");
                             int i =1/0; //如果发生异常,jvm会将锁释放
                             Thread.sleep(5000);
                             System.out.println(this.getName()+"醒了");
                             System.out.println (this.getName () + "End");
                           } the catch (InterruptedException E) {
                                   e.printStackTrace ();
                               }
                        }
                      }
               } .start ();
               new new the Thread ( "Thread2") {
                       public void RUN () {
                              before when synchronized (mySynchronized) {// compete for the same lock, did not release the thread 1, thread 2 can only wait
                              // synchronized (mySynchronized2) {// If it is not a lock, you can see two things at the same time printing
                              System.out.println (this.getName () + "start ");
                              System.out.println(this.getName()+" end");
                             }
                       }
               }.start();
      }
}

 

synchronized defect: it will reduce the efficiency of the system

 

If a block of code is synchronized modified, and when one thread acquires the corresponding lock, and executes the code block, then other threads can only have been waiting, waiting to acquire the lock thread releases the lock, the lock here and get the thread releases the lock only there are two issues:

 

1 ) to obtain the lock over this block of code execution thread, then the thread releases the possession of the lock;

 

2 ) abnormal thread execution has occurred and the JVM will automatically thread releases the lock.

 

Guess you like

Origin www.cnblogs.com/paradis/p/11429976.html