我们平时所用的++a并不是线程安全的,也不是原子操作,这里的++a其实包含了三个原子操作,但是对于这样的对变量直接操作怎样才能使其安全呢?这时,我们需要使用AtomicInteger。
关于AtomicInteger,自带++操作方法,之所以安全,是因为他对变量使用了volatile关键字。
import java.util.Timer;
import java.util.TimerTask;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.atomic.AtomicInteger;
public class AtomicIntegerTest implements Runnable {
private AtomicInteger i = new AtomicInteger(0);
public int getValue() {
return i.get();
}
private void evenIncrement() {
i.addAndGet(2);
}
@Override
public void run() {
while (true) {
evenIncrement();
}
}
public static void main(String[] args) {
//定时执行任务
new Timer().schedule(new TimerTask() {
@Override
public void run() {
System.err.println("Aborting");
System.exit(0);
}
}, 5000);
ExecutorService exec = Executors.newCachedThreadPool();
AtomicIntegerTest ait = new AtomicIntegerTest();
exec.execute(ait);
while (true) {
int val = ait.getValue();
if (val % 2 != 0) {
System.out.println(val);
System.exit(0);
}
}
}
}
用法如上,对着写就是了,在提个问题,下面这段代码有什么区别?
// 代码1
public class Sample {
private static int count = 0;
synchronized public static void increment() {
count++;
}
}
// 代码2
public class Sample {
private static AtomicInteger count = new AtomicInteger(0);
public static void increment() {
count.getAndIncrement();
}
}