一、线程安全
二、Java 语言中的线程安全
执行结果:
三、线程安全的实现方法
在 synchronized 能实现需求的情况下,优先考虑使用 synchronized 来进行同步
具体的案例可参考:一篇文章带你深入了解 volatile 与 Java 内存模型(JMM)
public class VolatileTest {
public static AtomicInteger race = new AtomicInteger(0);
public static void increase() {
race.incrementAndGet();
}
private static final int COUNT = 20;
public static void main(String[] args) {
Thread[] threads = new Thread[COUNT];
for (int i = 0; i < COUNT; i++) {
threads[i] = new Thread(new Runnable() {
@Override
public void run() {
for (int j = 0; j < 10000; j++) {
increase();
}
}
});
threads[i].start();
}
System.out.println(Thread.activeCount());
// while (Thread.activeCount() > 1) {
// System.out.println(Thread.activeCount());
// Thread.yield();
// }
System.out.println(race);
}
}