How can data be synchronized in Java?

In Java, there are several ways to achieve data synchronization:

  1. By using the synchronized keyword, it can be applied to methods or code blocks to ensure that only one thread executes the synchronized method or code block at a time, achieving data synchronization.
public synchronized void synchronizedMethod() {
    // 同步代码块
    synchronized (this) {
        // 需要同步的代码
    }
}
  1. Utilizing the ReentrantLock class: The ReentrantLock class offers similar functionality to the synchronized keyword, where locks can be acquired by calling the lock() method and released by calling the unlock() method.
Lock lock = new ReentrantLock();

public void synchronizedMethod() {
    lock.lock();
    try {
        // 需要同步的代码
    } finally {
        lock.unlock();
    }
}
  1. By using the wait() and notify() methods, a current thread will wait until another thread calls either notify() or notifyAll() to wake it up. These methods can be utilized to achieve thread synchronization and facilitate communication between threads.
Object lock = new Object();

public void synchronizedMethod() {
    synchronized (lock) {
        try {
            // 线程等待
            lock.wait();
            // 需要同步的代码
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

public void notifyMethod() {
    synchronized (lock) {
        // 唤醒等待的线程
        lock.notify();
    }
}

It is important to note that all three methods mentioned can achieve data synchronization, but different methods should be chosen in different scenarios. For example, the synchronized keyword and ReentrantLock class are suitable for locking code blocks or methods, while the wait() and notify() methods are suitable for scenarios involving thread wait and notification.

bannerAds