• 多线程的基础知识


    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;
            }
        }
    }
  • 相关阅读:
    multipart/form-data同时传递文本和多文件参数controller接收
    sonar配置记录一下经常找不到
    神经网络分类知识蒸馏
    jconsole监听JVM
    Cocos2dx在安卓平台下获取到assets目录下文件的绝对路径
    打印100以内的质数及优化
    VBA调用百度翻译API
    VBA调用百度智能云的文字识别获取图片中的数字
    象棋的思考方法讨论
    やさしい日本語2019 学习方法
  • 原文地址:https://www.cnblogs.com/zhihuayun/p/6866414.html
Copyright © 2020-2023  润新知