java乐观锁实现代码怎么写

   2024-10-12 9080
核心提示:在 Java 中,可以使用 synchronized 关键字或者 ReentrantLock 类来实现乐观锁。下面分别给出两种实现方式的示例代码:使用 sync

在 Java 中,可以使用 synchronized 关键字或者 ReentrantLock 类来实现乐观锁。下面分别给出两种实现方式的示例代码:

使用 synchronized 关键字实现乐观锁:
public class OptimisticLockExample {    private int count = 0;    public synchronized void increment() {        int oldValue = count;        int newValue = oldValue + 1;        // 模拟耗时操作        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);    }}
使用 ReentrantLock 类实现乐观锁:
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;            // 模拟耗时操作            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 中实现乐观锁的方式,分别使用 synchronized 关键字和 ReentrantLock 类。在实际开发中,可以根据具体场景选择合适的方式来实现乐观锁。

 
举报打赏
 
更多>同类维修大全
推荐图文
推荐维修大全
点击排行

网站首页  |  关于我们  |  联系方式网站留言    |  赣ICP备2021007278号