多线程的基础知识

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;
        }
    }
}

 

posted on 2017-05-17 10:53  heartzhizi  阅读(253)  评论(0编辑  收藏  举报

导航