Usage and feature analysis of Java synchronized keyword

Time:2021-7-25

This article mainly introduces the usage and feature analysis of Java synchronized keywords. It is introduced in great detail through the example code, which has a certain reference value for everyone’s study or work. Friends in need can refer to it

The synchronized keyword is a way to implement locks. It is an unfair lock implemented at the JVM level. The following are four ways to use synchronized

Synchronized properties:

1. Unfair lock

2. Reentrancy

1. It acts on the method to ensure the thread synchronization of the same method accessing the same object

public synchronized void testFun(String str){
  for(int i=0;i<15;i++){
    System. Out. Println (STR + ", executing...);
  }
}

2. Lock the object to ensure the synchronization of threads accessing the same object at the same time

public void testObject(String str){
  synchronized (this){
    for(int i=0; i<15;i++){
      System. Out. Println (STR + ", executing");
    }
  }
}

1. The two locking methods are the same in form

public static void main(String[] args){
  ExecutorService executorService = Executors.newCachedThreadPool();

  SynchronizeTest1 synchronizeTest1 = new SynchronizeTest1();
  executorService.execute(new Runnable() {
    @Override
    public void run() {
      Synchronizetes1.testobject ("thread 1");
    }
  });

  executorService.execute(new Runnable() {
    @Override
    public void run() {
      Synchronizetes1.testobject ("thread 2");
    }
  });
}

3. Act on class

public static void testClass(String str){
  synchronized (SynchronizeTest2.class){
    for(int i=0 ;i<15;i++){
      System. Out. Println (STR + ", executing");
    }
  }
}

4. Act on static methods

public synchronized static void testStaticFun(String str){
  for(int i=0;i<15;i++){
    System. Out. Println (STR + ", executing");
  }
}

3 and 4 are the same in form

public static void main(String[] args){
  ExecutorService executorService = Executors.newCachedThreadPool();

  executorService.execute(new Runnable() {
    @Override
    public void run() {
      Testclass ("thread 1")// You can replace it with the teststaticfun method
    }
  });

  executorService.execute(new Runnable() {
    @Override
    public void run() {
      Testclass ("thread 2")// You can replace it with the teststaticfun method
    }
  });

  executorService.shutdown();

}

The above is the whole content of this article. I hope it will be helpful to your study, and I hope you can support developpaer.