写一个程序,证明AtomXXX类比synchronized更高效
static Object obj = new Object();
AtomicInteger atomicInteger = new AtomicInteger();
int count = 0;
public static void main(String[] args) {
T1 z = new T1();
long time1 = time(z::m);
System.out.println(z.atomicInteger);
long time2 = time(z::m2);
System.out.println(z.count);
try {
TimeUnit.SECONDS.sleep(12);
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
System.out.println("AtomicXxx");
System.out.println(time1);
System.out.println("synchronized");
System.out.println(time2);
}
private static long time(Runnable runnable) {
List<Thread> threads = new ArrayList<>();
long startTime = System.currentTimeMillis();
for (int i = 0; i < 10; i++) {
threads.add(new Thread(runnable, "thread-" + i));
}
threads.forEach(Thread::start);
threads.forEach(o -> {
try {
o.join();
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
});
long endTime = System.currentTimeMillis();
return endTime - startTime;
}
void m (){
for (int i = 0; i < 1000000; i++) {
atomicInteger.incrementAndGet();
}
}
void m2() {
for (int i = 0; i < 1000000; i++) {
synchronized (this) {
count++;
}
}
}