线程同步和并发

  • CPU-高速缓存-主存
    在主流计算机的设计中,CPU的运算速度比主内存的读写速度要快得多,这就使得CPU在访问内存时要花很长时间来等待内存的操作,这种空等造成了系统整体性能的下降。为了解决这种速度上的不匹配问题,我们在CPU与主内存之间加入了比主内存要快的SRAM(Static Ram,静态存储器)。SRAM储存了主内存的映象,使CPU可以直接通过访问SRAM来完成数据的读写。由于SRAM的速度与CPU的速度相当,从而大大缩短了数据读写的等待时间,系统的整体速度也自然得到提高。 高速缓存即 Cache,就是指介于CPU与主内存之间的高速存储器(通常由静态存储器SRAM构成)。
    Cache的工作原理是基于程序访问的局部性。依据局部性原理,可以在主存和CPU通用寄存器之间设置一个高速的容量相对较小的存储器,把正在执行的指令地址附近的一部分指令或数据从主存调入这个存储器,供CPU在一段时间内使用。这对提高程序的运行速度有很大的作用。这个介于主存和CPU之间的高速小容量存储器称作高速缓冲存储器(Cache)。
    顺序流程.jpg

每个线程都有自己的高速缓存,在多线并发过程中,会导致CPU访问到高速缓存的数据不一致,从而导致线程并发问题。

  • 并发的三个概念

    • 原子性

      执行不可以分割,代码1、2、3要么都执行,要么都不执行。例如A 汇钱给 B,需要保证在数据修改时,A和B的账户同时修改(成功),或者同时不修改(不成功)。

    • 可见性

      当多线程访问同一个共享变量时,一个线程修改变量的值,保证了其他线程及时可以看到变量的修改,例如:volatile 关键字,保证变量修改的可见性。

    • 有序性

      程序执行的顺序按照代码的先后顺序执行:在很多编译器中,会对处理指令重新排序,提高执行效率,但是只会排序于数据无关的语句,保持线程内结果一致性。例如:java内存模型中,有happens-before原则。在java中,重新指令排序不仅仅涉及到结果的一致性,还涉及到GC执行调用--重新排序的指令段执行时,触发GC会导致垃圾回收的不可靠,因此GC的触发并不是在所有的代码执行时都可以触发,而是存在一定的安全区域,在安全区域内才能触发GC,有兴趣的同事可以去深入了解一下。

  • 线程同步

    • Synchronized修饰

    synchronized可以保证变量的修改可见性和原子性,当前线程可以访问该变量,其他线程被阻塞住

    public synchronized void addSession(){
        mSessionCount++;
    }
    
    public void removeSession(){
        synchronized (this) {
            mSessionCount--;
        }
    }
  • volatile (保证可见性,不保证原子性)

volatile本质是:jvm当前变量在寄存器中的值是不确定的,需要从主存中读取

private volatile int mSessionCount;
  • 原子类(AtomicInterger, AtomicBoolean ......)
  • lock锁

lock锁的状态是可见的,lock锁的类型比较多:可重入锁,读写锁,使用方法更加灵活。lock必须在finally释放,否则可能会造成异常情况下,锁无法释放

    ReentrantLock mLock = new ReentrantLock();
    public void addSession(){
        mLock.lock();
        try{
            mSessionCount++;
        }finally{
            mLock.unlock();
        }
        
    }
  • 容器类

ConcurrentHashMap BlockingQueue等数据结构
在java中,由于hashmap等容器是非线程安全的,java提供对用concurrentXXX数据结构,多线程安全,而且效率非常高,有兴趣的同事可以去看下

  • ThreadLocal

ThreadLocal比较常用,其本质不是线程同步,而是以空间换时间,每个线程维护自己的副本(在后台并发时比较有用)

    private static ThreadLocal<Integer> sCount = new ThreadLocal<Integer>();
    public void addSession(int count){
        count = ((sCount.get() == null) ? 0 : sCount.get()) + count;  
        sCount.set(count);
    }
    
    public int getSession(){
        return sCount.get();
    }

测试:

for(int i = 0; i < 5; i++){
    new Thread(new Runnable() {
        public void run() {
            s.addSession(1);
            System.out.println("session count : " + s.getSession());
        }
    }).start();
}

结果:

session count : 1
session count : 1
session count : 1
session count : 1
session count : 1

其原因是ThreadLocal在ThreadLocalMap中为每个线程保存了副本,map的key就是Thread本身,ThreadLocalMap持有ThreadLocal的弱引用,保证线程释放资源时的内存泄露问题(ThreadLoacl变量建议设置成private static),ThreadLocal:

static class ThreadLocalMap {

        /**
         * The entries in this hash map extend WeakReference, using
         * its main ref field as the key (which is always a
         * ThreadLocal object).  Note that null keys (i.e. entry.get()
         * == null) mean that the key is no longer referenced, so the
         * entry can be expunged from table.  Such entries are referred to
         * as "stale entries" in the code that follows.
         */
        static class Entry extends WeakReference<ThreadLocal<?>> {
            /** The value associated with this ThreadLocal. */
            Object value;

            Entry(ThreadLocal<?> k, Object v) {
                super(k);
                value = v;
            }
        }

    /**
     * Sets the current thread's copy of this thread-local variable
     * to the specified value.  Most subclasses will have no need to
     * override this method, relying solely on the {@link #initialValue}
     * method to set the values of thread-locals.
     *
     * @param value the value to be stored in the current thread's copy of
     *        this thread-local.
     */
    public void set(T value) {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
    }

    /**
     * Removes the current thread's value for this thread-local
     * variable.  If this thread-local variable is subsequently
     * {@linkplain #get read} by the current thread, its value will be
     * reinitialized by invoking its {@link #initialValue} method,
     * unless its value is {@linkplain #set set} by the current thread
     * in the interim.  This may result in multiple invocations of the
     * {@code initialValue} method in the current thread.
     *
     * @since 1.5
     */
     public void remove() {
         ThreadLocalMap m = getMap(Thread.currentThread());
         if (m != null)
             m.remove(this);
     }
  • 总结
    以上简单描述了CPU-Cache-主存模型,并发和线程同步,具体的实现大家可以多看看源码和第三方开源框架,里面很多设计非常值得我们学习和借鉴。
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 本文是我自己在秋招复习时的读书笔记,整理的知识点,也是为了防止忘记,尊重劳动成果,转载注明出处哦!如果你也喜欢,那...
    波波波先森阅读 13,905评论 4 56
  • CPU Cache 今天的CPU比25年前更复杂。那时候,CPU内核的频率与内存总线的频率相当。内存访问只比寄存器...
    blueshadow阅读 8,301评论 0 5
  • 从三月份找实习到现在,面了一些公司,挂了不少,但最终还是拿到小米、百度、阿里、京东、新浪、CVTE、乐视家的研发岗...
    时芥蓝阅读 42,542评论 11 349
  • 戏子有点儿痞阅读 1,544评论 0 0
  • 暮色四合,虫鸣渐起。未知的黑暗深处,我跋山涉水而来。寻找光明或者说扑火是我的宿命,不管怎样我都会拥抱着火...
    鲣鱼干阅读 1,580评论 0 0

友情链接更多精彩内容