Jakartase_Multithread--Thread Synchronization Method--Synchronization Block

Posted by emilyfrazier on Wed, 24 Jul 2019 04:22:02 +0200

Introduction and outline

  • One of the most common situations that occur in concurrent programming is that more than one thread of execution uses shared resources. In concurrency
    In an application, it is normal for multiple threads to read or write the same data or access the same file or database connection.
    . These shared resources can cause errors or data inconsistencies, and we must avoid these errors through some mechanisms.
  • Critical Zone: A block of code that accesses the same shared resource and cannot be executed by more than one thread at the same time.
  • Synchronization mechanism: When a thread wants to access a critical area, it uses one of the synchronization mechanisms to find out whether any other thread is executing the critical area.

    • If not, the thread enters the critical zone.
    • Otherwise, the thread pauses through the synchronization mechanism until another thread finishes executing the critical zone.
    • When multiple threads are waiting for a critical area for a thread to complete execution, the JVM selects one thread to execute, and the rest of the threads wait until their turn.
  • Java synchronized block s are used to mark methods or code blocks that are synchronized.
  • outline

       1. Java Synchronization Keyword
       2. Synchronization of Instance Method
       3. Static Method Synchronization
       4. Synchronization Block in Example Method
       5. Synchronization Block in Static Method
       6. Java Synchronization Example
    

2. Specific introduction

2.1. Java synchronized Keyword

  • 2.1.1. Role

    • Synchronized blocks in Java are marked with synchronized tags. Synchronization blocks are synchronized on an object in Java. All synchronization blocks synchronized on an object can only be entered and operated by one thread at the same time. All other threads waiting to enter the synchronization block will be blocked until the thread in the execution block exits.
  • 2.1.2. Principle

    • In java, each object has and has only one synchronization lock. This also means that synchronization locks are object-dependent. When we call the synchronized method of an object, we get the synchronized lock of that object.
  • 2.1.3. Classification of Synchronization Blocks

           Example method
           Static method
           Synchronization Block in Instance Method
           Synchronization Block in Static Method
     - The above synchronization blocks are synchronized on different ** objects **. The actual need for that synchronization block depends on the specific situation.
    
  • Synchronization of Example Method

       Writing 1: Modifying is a method
       public synchronized void method1 (int a){
           //do something;
       }
       Writing 2: Modified by a block of code that locks down the entire method
       public void method1 (int a){
           synchronized (this) { //do something; }
       }
     - Synchronization object: Actually, the object ** that calls this ** method is locked, commonly known as "object lock".
     - Notes:
         synchronized keywords cannot be used when defining interface methods.
         The constructor cannot use the synchronized keyword, but it can use the synchronized code block to synchronize.
  • (2) Static method synchronization

       public static synchronized void method2 (int a){
           //do something!
       }
     - **Synchronization object**: The object of action is all objects of the class (static methods belong to the class but not to the object)
     - **demo**
         public class SyncThread implements Runnable{
             private static int count;
             public SyncThread() {
                 count = 0;
             }    
             public synchronized static void method(){
                 for (int i = 0; i < 3; i++){
                     try {
                         System.out.println(Thread.currentThread().getName() + ":" + (count++));
                         Thread.sleep(100);
                     }catch (InterruptedException e){
                         e.printStackTrace();
                     }
                 }//for
             }//method
             public synchronized void run() {
                 method();
             }
         }//SynThread
         
         //In main: there are two different examples
         SyncThread syncThread1 = new SyncThread();
         SyncThread syncThread2 = new SyncThread();
         new Thread(syncThread1, "SyncThread1").start();
         new Thread(syncThread2, "SyncThread2").start();
         
           //Output:
           SyncThread1:0 
           SyncThread1:1 
           SyncThread1:2 
           SyncThread1:3 
           SyncThread1:4 
           SyncThread2:5 
           SyncThread2:6  Three loops were executed, respectively.
        - **Result:****syncThread1**and**syncThread2**yes**SyncThread**Two examples, but**thread1**and**thread2**Concurrent execution is maintained**Thread synchronization**
        - **Analysis:**`run()`The static method is called in`method()`,and**Static method**It belongs to the class, so syncThread1 and syncThread2 Equivalent to the use of**The same lock**. 
        - Static methods in modifying classes == Modify a class`synchronized(SyncThread.class){}`
  • (3) Synchronization block in the method

      public  class MyClass {
          public synchronized void log1(String msg1, String msg2){
               log.writeln(msg1);
               log.writeln(msg2);
          }
          public void log2(String msg1, String msg2){
               synchronized(this){
                   log.writeln(msg1);
                   log.writeln(msg2);
               }
          }
      }
    • Analysis: Only one thread at a time can be executed in either of the two synchronization blocks, which is similar to the two methods in the 1.
  • (4) Synchronization Block in Static Method

      public  class MyClass {
          public static synchronized void log1(String msg1, String msg2){
               log.writeln(msg1);
               log.writeln(msg2);
          }
          public void log2(String msg1, String msg2){
               synchronized(MyClass.class){
                   log.writeln(msg1);
                   log.writeln(msg2);
               }
          }
      }
    • Analysis: Two methods are not allowed to be accessed by multiple threads at the same time

Summary

  • A. Whether the synchronized keyword is added to a method or an object, if the object it works on is non-static, the lock it obtains is the object.
  • B. If the synchronized object is a static method or a class, the lock it obtains is a class, and all objects of that class have the same lock.
  • C. Each object has only one lock associated with it. Whoever gets the lock can run the code it controls.
  • D. To achieve synchronization is costly and may even cause deadlock, so try to avoid unnecessary synchronization control.
  • E. Deadlock: Let's leave a suspense

Topics: Scala Java Programming Database jvm