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