zoukankan      html  css  js  c++  java
  • 多线程的基础知识

    1.Java中Runnable和Callable有什么不同?

      两者都代表要在不同的线程中完成的任务,其中,Runnable把需要完成的任务放在run方法里面。两者最大的不同在于Callable中的call方法会有返回值,还会抛出异常,而Runnable的run方法并没有这些,call的返回值是Future对象。

    2.无阻塞算法

      compareandset,即CAS,无阻塞算法;这是一个原子操作,在硬件层面实现的,java里的原子类操作的基础就是CAS算法。总过程就是取值-计算-比较,比如取出A的值是m(假设是int),int n = 计算m,判断A是否等于m,如果 A = m,说明在这期间,A的值没有被其他线程改变,那么对A赋新值A = n,并返回true;如果A!=m,返回false;比如原子类AtomicInteger中有几个方法比较重要;

    public class AtomicInteger extends Number implements java.io.Serializable {
        /**
         * Atomically sets the value to the given updated value
         * if the current value {@code ==} the expected value.
         *    如果value == expect ,那么 value =  update,并且返回true;否则,返回false; 
         */
        public final boolean compareAndSet(int expect, int update) {
            return unsafe.compareAndSwapInt(this, valueOffset, expect, update);
        
    
        }
     /**
         * Atomically adds the given value to the current value.
         *
         * @param delta the value to add
         * @return the updated value
         */
        public final int addAndGet(int delta) {
            for (;;) {
                int current = get();
                int next = current + delta;
                if (compareAndSet(current, next))
                    return next;
            }
        }   
        /**
         * Atomically decrements by one the current value.
         *
         * @return the updated value
         */
        public final int decrementAndGet() {
            for (;;) {
                int current = get();
                int next = current - 1;
                if (compareAndSet(current, next))
                    return next;
            }
        }
    }
  • 相关阅读:
    【原】【Git】EGit强制覆盖本地文件
    【EGit】The current branch is not configured for pull No value for key branch.master.merge found in config
    【转】【Egit】如何将eclipse中的项目上传至Git
    参加SAP VT项目有感
    2013_12_30 纪念
    2013 12 25 圣诞日
    gin系列-中间件
    gin系列- 路由及路由组
    gin系列-重定向
    gin系列-文件上传
  • 原文地址:https://www.cnblogs.com/zhihuayun/p/6866414.html
Copyright © 2011-2022 走看看