如下各种组合代码:
public class ExampleUnitTest {
private AtomicLong aTest1 = new AtomicLong(0);
private static AtomicLong aTest2 = new AtomicLong(0);
private volatile AtomicLong aTest3 = new AtomicLong(0);
private static volatile AtomicLong aTest4 = new AtomicLong(0);
private static volatile AtomicLong aTest5 = new AtomicLong(0);
private static volatile AtomicLong aTest6 = new AtomicLong(0);
private volatile long bTest = 0;
private long cTest = 0;
private static long dTest = 0;
private static volatile long eTest = 0;
@Test
public void testMutiThread() throws InterruptedException {
for (int i = 0; i < 10000; i++) {
new Thread(new Runnable() {
@Override
public void run() {
for (int b = 0; b < 10000; b++) {
aTest1.addAndGet(1);
aTest2.addAndGet(1);
aTest3.addAndGet(1);
aTest4.addAndGet(1);
aTest5.incrementAndGet();
aTest6.set(aTest6.get() + 1);
bTest += 1;
cTest += 1;
dTest += 1;
eTest += 1;
}
}
}).start();
}
sleepPrint();
sleepPrint();
sleepPrint();
}
private void sleepPrint() throws InterruptedException {
System.out.println("aTest1=" + aTest1.get());
System.out.println("aTest2=" + aTest2.get());
System.out.println("aTest3=" + aTest3.get());
System.out.println("aTest4=" + aTest4.get());
System.out.println("aTest5=" + aTest5.get());
System.out.println("aTest6=" + aTest6.get());
System.out.println("bTest=" + bTest);
System.out.println("cTest=" + cTest);
System.out.println("dTest=" + dTest);
System.out.println("eTest=" + eTest);
Thread.sleep(1000);
}
}
实际日志如下:
aTest1=99937040
aTest2=99982649
aTest3=99983574
aTest4=99984102
aTest5=99984557
aTest6=72110419
bTest=73125502
cTest=79656231
dTest=91396726
eTest=75477497
aTest1=100000000
aTest2=100000000
aTest3=100000000
aTest4=100000000
aTest5=100000000
aTest6=72122513
bTest=73138023
cTest=79668467
dTest=91409613
eTest=75488925
aTest1=100000000
aTest2=100000000
aTest3=100000000
aTest4=100000000
aTest5=100000000
aTest6=72122513
bTest=73138023
cTest=79668467
dTest=91409613
eTest=75488925