温馨提示×

java多线程乐观锁实现代码怎么写

小亿
96
2023-11-15 20:02:14
栏目: 编程语言

乐观锁是一种乐观地认为并发访问不会发生冲突的锁机制,它适用于读多写少的场景。在Java中,可以使用AtomicInteger类来实现乐观锁。

下面是一个简单的示例代码,演示了如何使用乐观锁实现多线程并发访问共享变量的功能:

import java.util.concurrent.atomic.AtomicInteger;

public class OptimisticLockExample {
    private static AtomicInteger counter = new AtomicInteger(0);

    public static void main(String[] args) {
        Thread thread1 = new Thread(new IncrementTask());
        Thread thread2 = new Thread(new IncrementTask());

        thread1.start();
        thread2.start();

        try {
            // 等待线程执行完成
            thread1.join();
            thread2.join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println("Counter: " + counter);
    }

    static class IncrementTask implements Runnable {
        @Override
        public void run() {
            int oldValue, newValue;
            do {
                oldValue = counter.get();
                newValue = oldValue + 1;
            } while (!counter.compareAndSet(oldValue, newValue));
        }
    }
}

在上面的代码中,我们使用AtomicInteger类来定义一个共享变量counter。在每个线程的run方法中,我们通过循环读取和更新counter的值,直到成功执行compareAndSet方法将新值写入counter中。这样可以确保多个线程并发修改counter时不会出现冲突。

需要注意的是,乐观锁适用于读多写少的场景,如果并发写操作非常频繁,乐观锁的性能可能会受到影响。在这种情况下,可以考虑使用悲观锁来保证数据的一致性。

0