volatile与synchronized对数值进行操作时,可以保证数据的正确性,但后者速度更快
代码如下:
public class T7 {
volatile static int num = 0;
static CountDownLatch latch = new CountDownLatch(100);
//volatile线程可见
static volatile AtomicInteger a = new AtomicInteger();
public static void main(String[] args) {
var s = System.currentTimeMillis();
for (int i = 0; i < 100; i++) {
T7 tt = new T7();
new Thread(T7::ss, "T" + i).start();
}
//new Thread(T7::s1).start();
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(System.currentTimeMillis() - s);
}
static void s1() {
try {
latch.await();
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(a);
}
synchronized static void ss1() {
for (int i = 0; i < 1000; i++) {
num++;
}
latch.countDown();
}
static void ss() {
for (int i = 0; i < 1000; i++) {
a.incrementAndGet();
}
latch.countDown();
}
}