package atomadder;
import java.text.MessageFormat;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.atomic.LongAdder;
import java.util.logging.Logger;
public class test {
private static Logger logger = Logger.getLogger("LoggingDemo");
public static void atomicLong() throws Throwable {
final int threadCount = 32;
final AtomicLong longValue = new AtomicLong();
Thread[] threads = new Thread[threadCount];
for(int i=0; i<threadCount; i++){
threads[i] = new Thread(new Runnable() {
@Override
public void run() {
for(int i=0; i<100*10000; i++){
longValue.incrementAndGet();
}
}
});
}
long time = System.nanoTime();
for(int i=0; i<threadCount; i++){
threads[i].start();
}
for(int i=0; i<threadCount; i++){
threads[i].join();
}
StringBuilder sb= new StringBuilder();
//MessageFormat.format("我是{0},我来自{1},今年{2}岁", "中国人", "北京", "22");
logger.info(String.format("value: %d, time:%d", longValue.get(), System.nanoTime() - time));
logger.info(MessageFormat.format("value: {0}, time:{1}", longValue.get(), System.nanoTime() - time));
//logger.info("value: {}, time: {}", longValue.get(), System.nanoTime() - time);
}
public static void longAdder() throws Throwable {
final int threadCount = 32;
final LongAdder longAdder = new LongAdder();
Thread[] threads = new Thread[threadCount];
for(int i=0; i<threadCount; i++){
threads[i] = new Thread(new Runnable() {
@Override
public void run() {
for(int i=0; i<100*10000; i++){
longAdder.increment();
}
}
});
}
long time = System.nanoTime();
for(int i=0; i<threadCount; i++){
threads[i].start();
}
for(int i=0; i<threadCount; i++){
threads[i].join();
}
logger.info(MessageFormat.format("value: {0}, time: {1}", longAdder.longValue(), System.nanoTime() - time));
}
public static void main(String[] args) throws Throwable {
atomicLong();
logger.info("-----------------------");
longAdder();
}
}
结果:
十一月 29, 2019 10:12:14 下午 atomadder.test atomicLong
信息: value: 32000000, time:645934347
十一月 29, 2019 10:12:14 下午 atomadder.test atomicLong
信息: value: 32,000,000, time:704,913,473
十一月 29, 2019 10:12:14 下午 atomadder.test main
信息: -----------------------
十一月 29, 2019 10:12:15 下午 atomadder.test longAdder
信息: value: 32,000,000, time: 337,813,303