import java.util.concurrent.atomic.AtomicInteger; /**
* 原子操作的类 atomic
*/
public class VolatileDemo {
static AtomicInteger i = new AtomicInteger(0);
public static class PlusTask implements Runnable {
@Override
public void run() {
// synchronized (VolatileDemo.class){
for (int j = 0; j < 10000; j++) {
i.incrementAndGet(); //自增
}
// }
}
} public static void main(String[] args) throws InterruptedException{
Thread[] threads = new Thread[10];
for (int a = 0; a < 10; a++) {
threads[a] = new Thread(new PlusTask());
threads[a].start();
}
for (int a = 0; a < 10; a++) {
threads[a].join();
}
System.out.println(i.get());//i的值小于10000
}
}

import java.util.concurrent.atomic.AtomicInteger; /**
* 原子类型中的方法是保证了原子操作,但多个方法之间是没有原子性的
*/
public class AtomicIntegerDemo implements Runnable{
private static Integer count = 1;
private static AtomicInteger atomicInteger = new AtomicInteger(); @Override
public void run() {
while (true){
int c = getCountAtomic();
System.out.println(c);
if (c>=5){
break;
}
}
} // private Integer getCountAtomic() {
private synchronized Integer getCountAtomic() { //改进
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
if (atomicInteger.get()<5){
return atomicInteger.incrementAndGet();
}else {
return atomicInteger.get();
}
}
public static void main(String[] args){
AtomicIntegerDemo demo = new AtomicIntegerDemo();
Thread t1 = new Thread(demo);
Thread t2 = new Thread(demo);
t1.start();
t2.start();
}
//1
//2
//3
//4
//6
//5
//会出现6这种现象
//get方法和incrementAndGet方法都是原子操作,但复合使用时,无法保证原子性,仍旧可能出现数据错误
}
05-11 22:08