Home > Java > javaTutorial > Java test example to analyze the reentrant characteristics of ReentrantLock

Java test example to analyze the reentrant characteristics of ReentrantLock

WBOY
Release: 2023-05-09 18:07:08
forward
793 people have browsed it

1. Concept

A reentrant read-write lock. The read-write lock maintains a ReadLock and a WriteLock, and the underlying layer is AQS. , but AQS has only one state quantity. How to control reading and writing at the same time? The high 16 bits of state (int) are used here to represent the read status, the low 16 bits represent writing, and the high 16 bits represent the number of threads to obtain the read lock. ,The lower 16 bits represent the reentrant number of the ,write lock.

2. Principle

Use CAS AQS queue to implement. It supports fair locks and unfair locks. The implementation of both is similar to

3, example

public class ReentrantDemo implements Runnable {
    Lock lock = new ReentrantLock();
    @Override
    public void run() {
        set();
    }
    public void set() {
        try {
            lock.lock();
            System.out.println("set 方法");
            get();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();// 必须在finally中释放
        }
    }
 
    public void get() {
 
        try {
            lock.lock();
            System.out.println("get 方法");
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }
    public static void main(String[] args) {
        ReentrantDemo reentrantDemo = new ReentrantDemo();
        new Thread(reentrantDemo).start();
    }
}
Copy after login

The above is the detailed content of Java test example to analyze the reentrant characteristics of ReentrantLock. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:yisu.com
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template