Home Backend Development PHP Tutorial Detailed explanation of using synchronized to implement a Lock code

Detailed explanation of using synchronized to implement a Lock code

Dec 20, 2017 am 11:56 AM
lock synchronized

This article introduces how to use synchronized to implement a Lock code. The following is a practical case. Friends in need can refer to it.

Method one:

public synchronized void a(){
  //TODO
}
Copy after login


Method two:

public void b(){
  synchronized(this){
    //TODO
  }
}
Copy after login


From these two ways Look, the locks are all added between {}. Let’s take a look at how Lock is done:

public void c() {
  lock.lock();
  try {
    // TODO
  } finally {
    lock.unlock();
  }
}
Copy after login


The lock in this way is added between lock( ) and unlock(), so if you want to implement a lock function, you must think about how to implement these two methods, the lock() and unlock() methods. First define a framework as follows:

public void lock(){
}
public void unlock(){
}
Copy after login


Then think about how to use synchronized to implement these two methods.

Now I actually have a slightly clearer idea, but I still don’t know how to fill in these two methods. I will analyze the characteristics of Lock later, and then look at this code:

public void c() {
    lock.lock();
    //When current thread get the lock, other thread has to wait
    try {
        //current thread get in the lock, other thread can not get in
        // TODO
    }
    finally {
        lock.unlock();
        //current thread release the lock
    }
}
Copy after login


I just added a few comments to this code and did nothing else. Does it help to understand this code and see if it appears most frequently? What is the word? It is currentthread. So when we fill in the lock() and unlock() methods, should we pay attention to the keyword currentthread to find the solution? The answer is yes.

Next, analyze, how to make the thread wait when using synchronized? Use the wait() method. How to wake up the thread? Use the notify() method. Then use the wait() method in the lock() method and the notify() method in the unlock() method. So there is a condition when we use wait() and notify(). Think about what we should use as the condition?

We should use whether the current lock is occupied as a judgment condition. If the lock is occupied, currentthread waits. Think about whether we have always used this condition when using synchronized, the answer is yes.

Let’s analyze when to release the lock and what conditions are used. Think about it. If thread A gets the lock, can thread B release it? Of course not. If B could be released, it would violate the principle. Of course not. It must be that thread A's lock can only be released by thread A. So the judgment condition is to judge whether the thread holding the lock is currentthread. If so, it can be released. If not, of course it cannot.

Now let’s take a look at the complete code:

package test.lock;
import java.util.Random;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ThreadFactory;
public class NaiveLock {
    private static final long NONE = -1;
    private long owner = NONE;
    private Boolean isLooked() {
        return owner != NONE;
    }
    public synchronized void lock() {
        long currentThreadId = Thread.currentThread().getId();
        if (owner == currentThreadId) {
            throw new IllegalStateException("Lock has been acquired by current thread");
        }
        while (this.isLooked()) {
            System.out.println(String.format("thread %s is waitting lock", currentThreadId));
            try {
                wait();
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        owner = currentThreadId;
        System.out.println(String.format("Lock is acquired by thread %s", owner));
    }
    public synchronized void unlock() {
        if (!this.isLooked() || owner != Thread.currentThread().getId()) {
            throw new IllegalStateException("Only Lock owner can unlock the lock");
        }
        System.out.println(String.format("thread %s is unlocking", owner));
        System.out.println();
        owner = NONE;
        notify();
    }
    public static void main(String[] args) {
        final NaiveLock lock = new NaiveLock();
        ExecutorService executor = Executors.newFixedThreadPool(20, new ThreadFactory() {
            private ThreadGroup group = new ThreadGroup("test thread group");
            {
                group.setDaemon(true);
            }
            @Override
                  public Thread newThread(Runnable r) {
                return new Thread(group, r);
            }
        }
        );
        for (int i = 0; i < 20; i++) {
            executor.submit(new Runnable() {
                @Override
                        public void run() {
                    lock.lock();
                    System.out.println(String.format("thread %s is running...", Thread.currentThread().getId()));
                    try {
                        Thread.sleep(new Random().nextint(1000));
                    }
                    catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    lock.unlock();
                }
            }
            );
        }
    }
}
Copy after login


##Run it and see the result:

Lock is acquired by thread 8
thread 8 is running...
thread 27 is waitting lock
thread 26 is waitting lock
thread 25 is waitting lock
thread 24 is waitting lock
thread 23 is waitting lock
thread 22 is waitting lock
thread 21 is waitting lock
thread 20 is waitting lock
thread 19 is waitting lock
thread 18 is waitting lock
thread 17 is waitting lock
thread 16 is waitting lock
thread 15 is waitting lock
thread 14 is waitting lock
thread 13 is waitting lock
thread 12 is waitting lock
thread 11 is waitting lock
thread 10 is waitting lock
thread 9 is waitting lock
thread 8 is unlocking
  
Lock is acquired by thread 27
thread 27 is running...
thread 27 is unlocking
  
Lock is acquired by thread 26
thread 26 is running...
thread 26 is unlocking
  
Lock is acquired by thread 25
thread 25 is running...
thread 25 is unlocking
  
Lock is acquired by thread 24
thread 24 is running...
thread 24 is unlocking
  
Lock is acquired by thread 23
thread 23 is running...
thread 23 is unlocking
  
Lock is acquired by thread 22
thread 22 is running...
thread 22 is unlocking
  
Lock is acquired by thread 21
thread 21 is running...
thread 21 is unlocking
  
Lock is acquired by thread 20
thread 20 is running...
thread 20 is unlocking
  
Lock is acquired by thread 19
thread 19 is running...
thread 19 is unlocking
  
Lock is acquired by thread 18
thread 18 is running...
thread 18 is unlocking
  
Lock is acquired by thread 17
thread 17 is running...
thread 17 is unlocking
  
Lock is acquired by thread 16
thread 16 is running...
thread 16 is unlocking
  
Lock is acquired by thread 15
thread 15 is running...
thread 15 is unlocking
  
Lock is acquired by thread 14
thread 14 is running...
thread 14 is unlocking
  
Lock is acquired by thread 13
thread 13 is running...
thread 13 is unlocking
  
Lock is acquired by thread 12
thread 12 is running...
thread 12 is unlocking
  
Lock is acquired by thread 11
thread 11 is running...
thread 11 is unlocking
  
Lock is acquired by thread 10
thread 10 is running...
thread 10 is unlocking
  
Lock is acquired by thread 9
thread 9 is running...
thread 9 is unlocking
Copy after login


If you change the

for loop to 30 times, look at the result again:

Lock is acquired by thread 8
thread 8 is running...
thread 27 is waitting lock
thread 26 is waitting lock
thread 25 is waitting lock
thread 24 is waitting lock
thread 23 is waitting lock
thread 22 is waitting lock
thread 21 is waitting lock
thread 20 is waitting lock
thread 19 is waitting lock
thread 18 is waitting lock
thread 17 is waitting lock
thread 16 is waitting lock
thread 15 is waitting lock
thread 14 is waitting lock
thread 13 is waitting lock
thread 12 is waitting lock
thread 11 is waitting lock
thread 10 is waitting lock
thread 9 is waitting lock
thread 8 is unlocking
  
Lock is acquired by thread 27
thread 27 is running...
thread 8 is waitting lock
thread 27 is unlocking
  
Lock is acquired by thread 27
thread 27 is running...
thread 26 is waitting lock
thread 27 is unlocking
  
Lock is acquired by thread 27
thread 27 is running...
thread 25 is waitting lock
thread 27 is unlocking
  
Lock is acquired by thread 24
thread 24 is running...
thread 27 is waitting lock
thread 24 is unlocking
  
Lock is acquired by thread 23
thread 23 is running...
thread 24 is waitting lock
thread 23 is unlocking
  
Lock is acquired by thread 22
thread 22 is running...
thread 23 is waitting lock
thread 22 is unlocking
  
Lock is acquired by thread 22
thread 22 is running...
thread 21 is waitting lock
thread 22 is unlocking
  
Lock is acquired by thread 22
thread 22 is running...
thread 20 is waitting lock
thread 22 is unlocking
  
Lock is acquired by thread 22
thread 22 is running...
thread 19 is waitting lock
thread 22 is unlocking
  
Lock is acquired by thread 22
thread 22 is running...
thread 18 is waitting lock
thread 22 is unlocking
  
Lock is acquired by thread 17
thread 17 is running...
thread 17 is unlocking
  
Lock is acquired by thread 16
thread 16 is running...
thread 16 is unlocking
  
Lock is acquired by thread 15
thread 15 is running...
thread 15 is unlocking
  
Lock is acquired by thread 14
thread 14 is running...
thread 14 is unlocking
  
Lock is acquired by thread 13
thread 13 is running...
thread 13 is unlocking
  
Lock is acquired by thread 12
thread 12 is running...
thread 12 is unlocking
  
Lock is acquired by thread 11
thread 11 is running...
thread 11 is unlocking
  
Lock is acquired by thread 10
thread 10 is running...
thread 10 is unlocking
  
Lock is acquired by thread 9
thread 9 is running...
thread 9 is unlocking
  
Lock is acquired by thread 8
thread 8 is running...
thread 8 is unlocking
  
Lock is acquired by thread 26
thread 26 is running...
thread 26 is unlocking
  
Lock is acquired by thread 25
thread 25 is running...
thread 25 is unlocking
  
Lock is acquired by thread 27
thread 27 is running...
thread 27 is unlocking
  
Lock is acquired by thread 24
thread 24 is running...
thread 24 is unlocking
  
Lock is acquired by thread 23
thread 23 is running...
thread 23 is unlocking
  
Lock is acquired by thread 21
thread 21 is running...
thread 21 is unlocking
  
Lock is acquired by thread 20
thread 20 is running...
thread 20 is unlocking
  
Lock is acquired by thread 19
thread 19 is running...
thread 19 is unlocking
  
Lock is acquired by thread 18
thread 18 is running...
thread 18 is unlocking
Copy after login


I believe you have mastered the methods after reading these cases. For more exciting information, please pay attention to other related articles on the PHP Chinese website!

Related reading:

Detailed code examples of how to implement stack data structure and bracket matching algorithm in php

The most popular in php Simple string matching algorithm, php matching algorithm_PHP tutorial

The simplest string matching algorithm tutorial in php

The above is the detailed content of Detailed explanation of using synchronized to implement a Lock code. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Chat Commands and How to Use Them
4 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

How to use Lock in Java multithreading How to use Lock in Java multithreading May 12, 2023 pm 02:46 PM

After Jdk1.5, under the java.util.concurrent.locks package, there is a set of interfaces and classes for thread synchronization. When it comes to thread synchronization, everyone may think of the synchronized keyword, which is a built-in keyword in Java. It handles thread synchronization, but this keyword has many flaws and is not very convenient and intuitive to use, so Lock appears. Below, we will compare and explain Lock. Usually when we use the synchronized keyword, we will encounter the following problems: (1) Uncontrollability, unable to lock and release locks at will. (2) The efficiency is relatively low. For example, we are currently reading two files concurrently.

The principles and usage scenarios of Synchronized in Java and the usage and difference analysis of the Callable interface The principles and usage scenarios of Synchronized in Java and the usage and difference analysis of the Callable interface Apr 21, 2023 am 08:04 AM

1. Basic features 1. It starts with an optimistic lock, and if lock conflicts are frequent, it is converted to a pessimistic lock. 2. It starts with a lightweight lock implementation, and if the lock is held for a long time, it is converted to a heavyweight lock. 3. The spin lock strategy that is most likely used when implementing lightweight locks 4. It is an unfair lock 5. It is a reentrant lock 6. It is not a read-write lock 2. The JVM will synchronize the locking process Locks are divided into no lock, biased lock, lightweight lock, and heavyweight lock states. It will be upgraded sequentially according to the situation. Biased lock assumes that the male protagonist is a lock and the female protagonist is a thread. If only this thread uses this lock, then the male protagonist and the female protagonist can live happily forever even if they do not get a marriage certificate (avoiding high-cost operations). But the female supporting role appears

What are the ways to use Lock in Java? What are the ways to use Lock in Java? Apr 23, 2023 pm 08:52 PM

1. Function (1) The Lock method to acquire locks supports interruption, no acquisition after timeout, and is non-blocking (2) It improves semantics. Where to lock and unlock must be written out (3) Lock explicit lock can bring us Comes with good flexibility, but at the same time we must manually release the lock (4) Support Condition condition object (5) Allow multiple reading threads to access shared resources at the same time 2.lock usage //Get the lock voidlock() //If the current thread has not If interrupted, acquire the lock voidlockInterruptibly()//Return a new Condition instance bound to this Lock instance ConditionnewCondition()//Lock only when called

What functionality does the Java Lock class provide? What functionality does the Java Lock class provide? Apr 21, 2023 am 08:16 AM

Note 1. Lock is an interface under the java.util.concurent package, which defines a series of locking operation methods. 2. The Lock interface mainly includes ReentrantLock, ReentrantReadWriteLock, ReentrantReadWriteLock, and WriteLock implementation classes. Different from Synchronized, Lock provides related interfaces such as acquiring locks and releasing locks, making it more flexible to use and more complex to operate. InstanceReentrantReadWriteLocklock=newReentrantReadWriteLock();Lockread

Java keyword synchronized principle and lock status example analysis Java keyword synchronized principle and lock status example analysis May 11, 2023 pm 03:25 PM

1. The concept of lock in Java Spin lock: When a thread acquires a lock, if the lock has been acquired by another thread, then the thread will wait in a loop, and then continue to judge whether the lock can be successfully acquired until it is acquired. The lock will exit the loop. Optimistic locking: Assuming there is no conflict, if the data is found to be inconsistent with the previously acquired data when modifying the data, the latest data will be read and the modification will be retried. Pessimistic lock: Assume that concurrency conflicts will occur, synchronize all data-related operations, and start locking from the time the data is read. Exclusive lock (write): Add a write lock to the resource. The thread can modify the resource, but other threads cannot lock it again (single write). Shared lock (read): After adding a read lock to a resource, it can only be read but not modified. Other threads can only add read locks and cannot add write locks (multiple). See as S

How to use synchronized to implement synchronization mechanism in Java? How to use synchronized to implement synchronization mechanism in Java? Apr 22, 2023 pm 02:46 PM

Summary of how to use synchronized in Java 1. When synchronized is used as a function modifier, the sample code is as follows: Publicsynchronizedvoidmethod(){//….} This is the synchronization method. So which object is synchronized locked at this time? What he locks is calling this synchronized method object. In other words, when an object P1 executes this synchronization method in different threads, they will form mutual exclusion to achieve synchronization effect. However, another object P2 generated by the Class to which this object belongs can arbitrarily call this method with the synchronized keyword added. The sample code above, etc.

What are the three synchronization methods in Java and how to use them? What are the three synchronization methods in Java and how to use them? Apr 27, 2023 am 09:34 AM

1. Explain that synchronized is our most commonly used synchronization method, and there are three main ways to use it. 2. Example//General class method synchronization synchronizedpublidvoidinvoke(){}//Class static method synchronization synchronizedpublicstaticvoidinvoke(){}//Code block synchronization synchronized(object){}The difference between these three methods is that the synchronized objects are different. Ordinary classes synchronize the object itself, static methods synchronize the Class itself, and code blocks synchronize the objects we fill in the brackets. What collections are there in Java?

What is the principle and process of Java Synchronized lock upgrade? What is the principle and process of Java Synchronized lock upgrade? Apr 19, 2023 pm 10:22 PM

Tool preparation Before we formally talk about the principle of synchronized, let's talk about spin locks first, because spin locks play a big role in the optimization of synchronized. To understand spin locks, we first need to understand what atomicity is. The so-called atomicity simply means that each operation is either not done or done. Doing all means that it cannot be interrupted during the operation. For example, to add one to the variable data, there are three steps: Load from memory into register. Add one to the value of data. Write the result back to memory. Atomicity means that when a thread is performing an increment operation, it cannot be interrupted by other threads. Only when this thread completes these three processes

See all articles