写一个程序,证明AtomXXX类比synchronized更高效
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
/**
* @author Mxhlin
* @Email fuhua277@163.com
* @Date 2022/10/09/14:57
* @Version
* @Description 6、写一个程序,证明AtomXXX类比synchronized更高效
*/
public class ZDemo05 {
static Object obj = new Object();
AtomicInteger atomicInteger = new AtomicInteger();
int count = 0;
public static void main(String[] args) {
ZDemo05 z = new ZDemo05();
// atomicxxx
long time1 = time(z::m);
System.out.println(z.atomicInteger);
// synchronized
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 < 100000000; i++) {
atomicInteger.incrementAndGet();// 原子操作
}
}
void m2() {
for (int i = 0; i < 100000000; i++) {
synchronized (this) {
count++;
}
}
}
}
运行结果: