在多线程中,当合并并发时,共享实体通常会导致问题。可变对象或变量等共享实体可能会被更改,这可能会导致程序或数据库的不一致。因此,在并发访问时处理共享实体变得至关重要。在这种情况下,原子变量可以是替代方案之一。
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;
需要原子变量
考虑下面的例子:
Java
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);
}
}
Java
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);
}
}
Java
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);
}
}
输出:
137754082
在单线程环境中,上述类只会给出预期的结果。但是当涉及到多线程环境时,可能会导致结果不一致。这是因为更新“var”分三个步骤完成:读取、更新和写入。如果两个或多个线程同时尝试更新该值,则它可能无法正确更新。
这个问题可以使用锁定和同步来解决,但效率不高。
1.使用锁类比或同步:同步或锁定可以解决我们的问题,但它会损害时间效率或性能。首先,它授权资源和线程调度器来控制锁。其次,当多个线程尝试获取锁时,只有其中一个线程获胜,其余线程被挂起或阻塞。暂停或阻塞线程会对性能产生巨大影响。
Java
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. 使用原子变量:
Java
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