java樂觀鎖實(shí)現(xiàn)代碼怎么寫

小億
119
2024-06-12 12:49:23

在 Java 中,可以使用 synchronized 關(guān)鍵字或者 ReentrantLock 類來實(shí)現(xiàn)樂觀鎖。下面分別給出兩種實(shí)現(xiàn)方式的示例代碼:

  1. 使用 synchronized 關(guān)鍵字實(shí)現(xiàn)樂觀鎖:
public class OptimisticLockExample {
    private int count = 0;

    public synchronized void increment() {
        int oldValue = count;
        int newValue = oldValue + 1;

        // 模擬耗時(shí)操作
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        count = newValue;
    }

    public static void main(String[] args) {
        OptimisticLockExample example = new OptimisticLockExample();

        Thread t1 = new Thread(() -> {
            example.increment();
        });

        Thread t2 = new Thread(() -> {
            example.increment();
        });

        t1.start();
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Final count: " + example.count);
    }
}
  1. 使用 ReentrantLock 類實(shí)現(xiàn)樂觀鎖:
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class OptimisticLockExample {
    private int count = 0;
    private Lock lock = new ReentrantLock();

    public void increment() {
        lock.lock();
        try {
            int oldValue = count;
            int newValue = oldValue + 1;

            // 模擬耗時(shí)操作
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            count = newValue;
        } finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        OptimisticLockExample example = new OptimisticLockExample();

        Thread t1 = new Thread(() -> {
            example.increment();
        });

        Thread t2 = new Thread(() -> {
            example.increment();
        });

        t1.start();
        t2.start();

        try {
            t1.join();
            t2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Final count: " + example.count);
    }
}

以上是兩種在 Java 中實(shí)現(xiàn)樂觀鎖的方式,分別使用 synchronized 關(guān)鍵字和 ReentrantLock 類。在實(shí)際開發(fā)中,可以根據(jù)具體場(chǎng)景選擇合適的方式來實(shí)現(xiàn)樂觀鎖。

0