How to replace synchronized with lock

Time:2021-10-22

In multithreading, before version 1.5, we used synchronous code blocks or synchronous methods to solve thread safety problems

For example:

Synchronous code block

Synchronized (lock object){

Function code;

  }

Synchronization method

  public synchronized void test(){

Function code;

  }

//Finish sharing data first

  class Person{

  String name;

  boolean isMoney=true;

//Earn money

  public void zhengQian(){

  synchronized(this){

  while(!isMoney){

  try{wait();}catch(Exception e){}

  }

Name = “man”;

System. Out. Println (www.sangpi. Comthread. Currentthread(). Getname() + name + “— make money –“);

  isMoney=!isMoney;

notifyAll();// Wake up all

  }

  }

//Spend money

  public void huaQian(){

  synchronized(this){

  while(isMoney){

  try{wait();}catch(Exception e){}

  }

Name = “women…”;

System. Out. Println (thread. Currentthread(). Getname() + name + “— spend = = = = = = = money –“);

  isMoney=!isMoney;

notifyAll();// Wake up all

  }

  }

  }

//Input thread

  class In implements Runnable{

  Person p=null;

  In(Person p){

  this.p=p;

  }

  public void run(){

  while(true){

  p.zhengQian();

  }

  }

  }

//Output thread

  class Out implements Runnable{

  Person p=null;

  Out(Person p){

  this.p=p;

  }

  public void run(){

  while(true){

  p.huaQian();

  }

  }

  }

It can be seen from the code that for synchronized code blocks or synchronization methods, the locked code is controlled by the lock object this.

The API also tells us:

The lock implementation provides a wider range of locking operations than can be obtained using synchronized methods and statements. This implementation allows a more flexible structure of page games, can have very different properties, and can support multiple related condition objects.

How to use lock + condition?

The code is as follows:

  import java.util.concurrent.locks.*;

  class Person{

  String name;

  boolean isMoney=true;

  Lock lock=new ReentrantLock();

  Condition in=lock.newCondition();

  Condition out=lock.newCondition();

//Earn money

  public void zhengQian(){

  lock.lock();

  try{

  while(!isMoney){

  try{in.wait();}catch(Exception e){}

  }

Name = “man”;

System. Out. Println (thread. Currentthread(). Getname() + name + “— make money –“);

  isMoney=!isMoney;

out.signal();// Wake each other up

  }finally{

  lock.unlock();

  }

  }

//Spend money

  public void huaQian(){

  lock.lock();

  try{

  while(!isMoney){

  try{out.wait();}catch(Exception e){}

  }

Name = “women…”;

System. Out. Println (thread. Currentthread(). Getname() + name + “— spend = = = = = = = money –“);

  isMoney=!isMoney;

in.signal();// Wake each other up

  }finally{

  lock.unlock();

  }

  }

  }

Through comparison, it is found that the lock + condition method uses the condition object to specifically operate the on-site waiting and wake-up,

That is, the production thread has a condition object dedicated to the generation thread and the consumer thread has a condition object dedicated to the consumer thread

Object, which thread can be precisely controlled when waiting or waking up, and the synchronization code block or synchronization method cannot be precisely controlled when waking up

Wake up the other party, so you can only wake up all. At this time, the judgment times of threads are increased. Obviously, lock + condition is better than synchronized

Next, let’s analyze the relationship between lock and condition

The subclass object of lock is to replace synchronized, that is, lock. Condition is only the operation object of lock

Instead of the previous lock objects, they all have wait and wake-up methods. Although their names are different, condition is mainly the operation object of the lock

A lock object creates three condition objects x, y, Z

In other words, the threads that execute the lock in the future will be divided into three types of threads. For example, if x.await() is executed, the code will be executed

The three green threads will enter the waiting state. For example, the three red threads in Z are in the waiting state. If z.signal() is executed, one of the three red threads executing Z will be awakened, so that the code can run normally.

The two sides of the blue line respectively represent the subclass objects of two locks. The conditions of each lock can operate with each other. For two locks

Conditions between locks, such as X and Q, have no direct relationship

Well, this article mainly explains the lock + condition method to replace synchronized. I hope it will be helpful to you.

Recommended Today

Go reflection class instance

Internal mechanism of variables Type information: static meta information, predefined Value information: it is dynamically changed during program operation Use of reflection Get type information: reflect.typeof, which is static Get value information: reflect.valueof, which is dynamic Get interface value information by reflection package main import ( “fmt” “reflect” ) //Get interface value information by reflection […]