Home  >  Article  >  Java  >  How to use locks and synchronizers in Java concurrent programming?

How to use locks and synchronizers in Java concurrent programming?

PHPz
PHPzOriginal
2024-05-08 22:06:02872browse

Java provides locks and synchronizers to manage access to shared resources. Locks such as ReentrantLock allow only one thread to access a critical section at a time, while synchronizers such as Semaphore and CountDownLatch provide more flexible concurrency control, such as limiting the number of threads accessing a resource simultaneously or waiting for all threads to complete their tasks. Using these mechanisms can effectively avoid data races and improve application performance.

Java 并发编程中如何使用锁和同步器?

Locks and synchronizers in Java concurrent programming

Concurrent programming allows multiple threads to execute at the same time, but requires a mechanism to manage Access to shared resources. Java provides various locks and synchronizers to achieve this.

Lock

Lock allows only one thread to access the critical section (modified part of the shared resource) at a time. Commonly used locks are:

// 创建一个 ReentrantLock
Lock lock = new ReentrantLock();

// 获取锁
lock.lock();

// 访问临界区
// ...

// 释放锁
lock.unlock();

Synchronizer

Synchronizer is more advanced than lock and provides more flexible concurrency control. Commonly used synchronizers are:

Semaphore

Semaphore limits the number of threads that can access resources at the same time.

// 创建一个 Semaphore,允许最多 3 个线程同时访问
Semaphore semaphore = new Semaphore(3);

// 申请许可证
semaphore.acquire();

// 访问临界区
// ...

// 释放许可证
semaphore.release();

CountDownLatch

CountDownLatch waits for all threads to complete their tasks before continuing.

// 创建一个 CountDownLatch,等待 10 个线程完成
CountDownLatch latch = new CountDownLatch(10);

// 10 个线程执行任务
// ...

// 每个线程完成后,计数器减一
latch.countDown();

// 主线程等待所有线程完成
latch.await();

Practical case

The following is a practical case of bank account operation, using Semaphore to limit the number of threads accessing the account at the same time:

class BankAccount {
    private Semaphore semaphore = new Semaphore(1);
    private double balance;

    public void deposit(double amount) {
        try {
            semaphore.acquire();
            balance += amount;
        } finally {
            semaphore.release();
        }
    }

    public void withdraw(double amount) {
        try {
            semaphore.acquire();
            balance -= amount;
        } finally {
            semaphore.release();
        }
    }
}

Conclusion

Locks and synchronizers are powerful tools for managing access to shared resources in Java concurrent programming. By using these mechanisms carefully, you can effectively avoid data races and improve program performance.

The above is the detailed content of How to use locks and synchronizers in Java concurrent programming?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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