多线程加法如何保证
我们先来看一下多线程直接相加的例子
public class CasDemo {
public static int count = 0;
public static void main(String[] args) {
//long startTime = System.currentTimeMillis();
//开启两个线程
for(int i = 0;i<2;i++) {
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(10);
}catch(InterruptedException e) {
e.printStackTrace();
}
//每个线程当中让count值自增100次
for(int j = 0;j<10000000;j++) {
//synchronized (CasDemo.class) {
count++;
//}
}
}}).start();
}
try {
Thread.sleep(2000);
}catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println("count="+count);
//long endTime = System.currentTimeMillis();
//System.out.println(endTime-startTime);
}
}
输出结果为count=10731025
可以看到这是一个错误的结果,那么如果保证多线程相加的安全呢。
采用java同步关键字synchronized
我们在循环里面添加synchronized
就可以了(也就是把上面注释的代码放开)。但是,这样子加同步锁,比较慢。怎么办呢,
这里还有别的方法
采用AtomicInteger类
package cc.flybb;
import java.util.concurrent.atomic.AtomicInteger;
public class CasDemo2 {
public static AtomicInteger count = new AtomicInteger(0);
public static void main(String[] args) {
//long startTime = System.currentTimeMillis();
//开启两个线程
for(int i = 0;i<2;i++) {
new Thread(new Runnable() {
@Override
public void run() {
try {
Thread.sleep(10);
}catch(InterruptedException e) {
e.printStackTrace();
}
//每个线程当中让count值自增100次
for(int j = 0;j<100000;j++) {
//synchronized (CasDemo2.class) {
count.incrementAndGet();
//}
}
}}).start();
}
try {
Thread.sleep(2000);
}catch(InterruptedException e) {
e.printStackTrace();
}
System.out.println("count="+count);
//long endTime = System.currentTimeMillis();
//System.out.println(endTime-startTime);
}
}
输出结果是一样的count=200000
。