c1- n++ 线程安全性demo

作者: 当当一丢丢 | 来源:发表于2018-08-25 13:32 被阅读26次
    UnsafeSequence
    package com.dang.book2.chapter1;
    
    /**
     * Created by Dangdang on 2018/7/16.
     * 非线程安全的数值生成器,非线程安全主要体现在 number++ 操作上,该操作并非原子性,包括3个连续动作
     * 从主存中取number -> 线程内存 number+1 -> 写回到主存number;<br>
     * 但由于执行很快,故本例的两个线程有可能未能体现出最终结果不等于99的现象
     */
    public class UnsafeSequence {
    
        private int number;
    
        /**
         * 返回唯一数值,将在多线程环境下运行
         *
         * @return
         */
        public int getNext() {
            try {
                Thread.sleep(10L);
            } catch (InterruptedException e) {
    
            }
            return number++;
        }
    
    }
    
    
    SafeSequence
    package com.dang.book2.chapter1;
    
    public class SafeSequence {
    
        private int number;
    
        /**
         * 返回唯一数值,将在多线程环境下运行
         *
         * @return
         */
        public synchronized int getNext() {
            try {
                Thread.sleep(10L);
            } catch (InterruptedException e) {
    
            }
            return number++;
        }
    
    }
    
    
    demo
    package com.dang.book2.chapter1;
    
    /**
     * Created by Dangdang on 2018/7/16.
     */
    public class SequenceDemo {
    
        public static void main(String[] args) {
    
            SequenceDemo demo = new SequenceDemo();
    
            //demo.unSafeTest();
            demo.safeTest();
    
        }
    
        public void unSafeTest() {
            //线程共享变量
            final UnsafeSequence sequence = new UnsafeSequence();
    
            //lambda 代替可以代替匿名内部类,也可直接将=右边表达式放到Thread参数中
            Runnable target = () -> {
                for (int i = 0; i < 50; i++) {
                    int next = sequence.getNext();
                    System.out.println(Thread.currentThread().getName() + ":" + next);
                }
            };
    
            Thread thread1 = new Thread(target);
            Thread thread2 = new Thread(target);
            thread1.start();
            thread2.start();
        }
    
        public void safeTest() {
            SafeSequence safeSequence = new SafeSequence();
    
            Runnable target2 = () -> {
                for (int i = 0; i < 50; i++) {
                    int next = safeSequence.getNext();
                    System.out.println(Thread.currentThread().getName() + ":" + next);
                }
            };
    
            Thread thread1 = new Thread(target2);
            Thread thread2 = new Thread(target2);
            thread1.start();
            thread2.start();
        }
    
    }
    
    

    相关文章

      网友评论

        本文标题:c1- n++ 线程安全性demo

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