美文网首页
volatile和synchronized运行比较

volatile和synchronized运行比较

作者: archerdu | 来源:发表于2021-08-06 14:36 被阅读0次
package springboot.concurrent;

/**
 * volatile和synchronized运行比较
 *
 * @author duxuefu
 * @since 2021/8/6 13:47
 */
public class VolatileTest {

    public static void main(String[] args) {
        VolatileModel volatileModel = new VolatileModel();

        for (int i = 0; i < 10; i++) {
            new Thread(volatileModel).start();
        }
        try {
            Thread.sleep(5000L);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("volatile 修饰字段   countA: " + volatileModel.countA);
        System.out.println("synchronized 代码块 countB: " + volatileModel.countB);
    }

    public static class VolatileModel implements Runnable {
        private volatile int countA = 0;
        private int countB = 0;

        @Override
        public void run() {
            // volatile 不是原子性
            for (int i = 0; i < 10000; i++) {
                countA++;
            }
            // synchronized 才是原子 性
            synchronized (this) {
                for (int i = 0; i < 10000; i++) {
                    countB++;
                }
            }
            System.out.println(Thread.currentThread().getName() + " 执行完成!");
        }
    }
}

执行结果:

Thread-0 执行完成!
Thread-1 执行完成!
Thread-2 执行完成!
Thread-3 执行完成!
Thread-4 执行完成!
Thread-5 执行完成!
Thread-6 执行完成!
Thread-7 执行完成!
Thread-8 执行完成!
Thread-9 执行完成!
volatile 修饰字段   countA: 99374
synchronized 代码块 countB: 100000

相关文章

网友评论

      本文标题:volatile和synchronized运行比较

      本文链接:https://www.haomeiwen.com/subject/ypnbvltx.html