标签:排序 exception number print 可见性 private class 技术 inf
/*
* 可见性和原子性的实例代码
* */
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
class MyData {
// volatile int number = 0;
volatile int number = 0;
/*public void addNumber() {
this.number = 60;
}*/
/*public synchronized void addNumber() {
this.number = 60;
}*/
public void addself() {
this.number++;
}
// AtomicInteger atomicInteger = new AtomicInteger();
AtomicInteger atomicInteger = new AtomicInteger();
public void atomicAddSelf() {
atomicInteger.getAndIncrement();
}
}
public class DemoVolatile {
public static void main(String[] args) {
// VisibilityVerificationVolatileDemo();
AtomicityVerificationVolatileDemo();
}
private static void AtomicityVerificationVolatileDemo() {
// 原子性验证
// 定义1000个线程,调用addSelf,查看最终结果,如果结果一致则表示原子性可以保证
MyData mydata = new MyData();
for (int i = 0; i < 20; i++) {
new Thread(() -> {
// 操作数据
for (int j = 0; j < 1000; j++) {
mydata.addself();
mydata.atomicAddSelf();
}
}, String.valueOf(i)).start();
}
while (Thread.activeCount() > 2) {
Thread.yield();
}
System.out.println("number ######### " + mydata.number);
System.out.println("atomicInteger ######### " + mydata.atomicInteger);
}
private static void VisibilityVerificationVolatileDemo() {
// 验证可见性
MyData myData = new MyData();
new Thread(() -> {
System.out.println(Thread.currentThread().getName() + " start \t");
try {
TimeUnit.SECONDS.sleep(3);
} catch (InterruptedException e) {
e.printStackTrace();
}
myData.addself();
System.out.println(Thread.currentThread().getName() + " update valus = " + myData.number);
}, "AAA").start();
while (myData.number == 0) {
}
System.out.println(Thread.currentThread().getName() + " is over ");
}
}
标签:排序 exception number print 可见性 private class 技术 inf
原文地址:https://www.cnblogs.com/cerofang/p/12684412.html