Java中的原子变量与示例

在多线程中,共享实体在合并并发时大多会导致问题。诸如可变对象或变量之类的共享实体可能会被更改,这可能会导致程序或数据库的不一致。因此,在并发访问时处理共享实体变得至关重要。在这种情况下,原子变量可以是替代方案之一。

Java 提供了原子类,例如AtomicInteger、AtomicLong、AtomicBoolean和AtomicReference。这些类的对象分别代表int、long、boolean和对象引用的原子变量。这些类包含以下方法。

set(int value):设置为给定值
get():获取当前值
lazySet(int value):最终设置为给定值
compareAndSet(int expect, int update):如果当前值 == 预期值,则自动将值设置为给定的更新值
addAndGet(int delta):以原子方式将给定值添加到当前值
decrementAndGet():以原子方式将当前值减一

例子:

// Atomic Variable
AtomicInteger var;

考虑以下示例:

class Counter extends Thread {
 
    // Counter Variable
    int count = 0;
 
    // method which would be called upon
    // the start of execution of a thread
    public void run()
    {
        int max = 1_000_00_000;
 
        // incrementing counter
        // total of max times
        for (int i = 0; i < max; i++) {
            count++;
        }
    }
}
 
public class UnSafeCounter {
    public static void main(String[] args)
        throws InterruptedException
    {
        // Instance of Counter Class
        Counter c = new Counter();
 
        // Defining Two different threads
        Thread first = new Thread(c, "First");
        Thread second = new Thread(c, "Second");
 
        // Threads start executing
        first.start();
        second.start();
 
        // main thread will wait for
        // both threads to get completed
        first.join();
        second.join();
 
        // Printing final value of count variable
        System.out.println(c.count);
    }
}

输出:

137754082

在单线程环境中,上述类只会给出预期的结果。但是当涉及到多线程环境时,可能会导致结果不一致。这是因为更新“var”分三个步骤完成:读取、更新和写入。如果两个或更多线程尝试同时更新该值,则它可能无法正确更新。

这个问题可以使用Lock 和 Synchronization解决,但效率不高。

1.使用锁类比或同步:同步或锁定可以解决我们的问题,但它会牺牲时间效率或性能。首先,它要求资源和线程调度程序控制锁。其次,当多个线程试图获取锁时,只有一个获胜,其余的被挂起或阻塞。暂停或阻塞线程会对性能产生巨大影响。

import java.io.*;
import java.util.concurrent.locks.*;
 
class Counter extends Thread {
 
    // Counter Variable
    int count = 0;
 
    // method which would be called upon
    // the start of execution of a thread
    public synchronized void run()
    {
 
        int max = 1_000_00_000;
 
        // incrementing counter total of max times
        for (int i = 0; i < max; i++) {
            count++;
        }
    }
}
 
public class SynchronizedCounter {
    public static void main(String[] args)
        throws InterruptedException
    {
        // Instance of Counter Class
        Counter c = new Counter();
 
        // Defining Two different threads
        Thread first = new Thread(c, "First");
        Thread second = new Thread(c, "Second");
 
        // Threads start executing
        first.start();
        second.start();
 
        // main thread will wait for both
        // threads to complete execution
        first.join();
        second.join();
 
        // Printing final value of count variable
        System.out.println(c.count);
    }
}

输出:

200000000

2.使用原子变量:

import java.util.concurrent.atomic.AtomicInteger;
 
class Counter extends Thread {
 
    // Atomic counter Variable
    AtomicInteger count;
 
    // Constructor of class
    Counter()
    {
        count = new AtomicInteger();
    }
 
    // method which would be called upon
    // the start of execution of a thread
    public void run()
    {
 
        int max = 1_000_00_000;
 
        // incrementing counter total of max times
        for (int i = 0; i < max; i++) {
            count.addAndGet(1);
        }
    }
}
 
public class AtomicCounter {
    public static void main(String[] args)
        throws InterruptedException
    {
        // Instance of Counter Class
        Counter c = new Counter();
 
        // Defining Two different threads
        Thread first = new Thread(c, "First");
        Thread second = new Thread(c, "Second");
 
        // Threads start executing
        first.start();
        second.start();
 
        // main thread will wait for both
        // threads to complete execution
        first.join();
        second.join();
 
        // Printing final value of count variable
        System.out.println(c.count);
    }
}

输出:

200000000
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

糖果Autosar

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值