手写 Volatile 、Synchronized 、线程池的使用场景

痞子三分冷 提交于 2019-12-14 23:24:54
import java.util.concurrent.ExecutorService;

import static java.util.concurrent.Executors.newFixedThreadPool;

public class Test {
    private static volatile int i = 0; //加 volatile 没用,它并不能保证原子性

    private static synchronized void increase() {
        //此处加上 Synchronized 可以解决问题,成功返回20000
        //这里加了 Synchronized 后就前面的 i 位置就不需要加 volatile 了
        i++;
    }

    public static void main(String[] args) throws InterruptedException {
        ExecutorService e = newFixedThreadPool(2);
        Runnable r = () -> {
            for (int j = 0; j < 10000; j++) {
                increase();
            }
        };
        e.execute(r);
        e.execute(r);
        Thread.sleep(1000);
        e.shutdown();
        System.out.println(i);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!