Java并发编程—线程间共享

并发编程—线程间共享

在这里我将会记录三块学习内容:Synchronized,ThreadLocal,Volatile

synchronized内置锁

由于同一进程的多个线程共享同一片存储空间,在带来方便的同时,也带来了访问冲突这个严重的问题。Java语言提供了专门机制以解决这种冲突,有效避免了同一个数据对象被多个线程同时访问。

synchronized作用域
  1. 对象锁:某个对象实例内,synchronized method(){}可以防止多个线程同时访问这个对象的synchronized方法。如果一个对象有多个synchronized方法,只要一个线 程访问了其中的一个synchronized方法,其它线程不能同时访问这个对象中任何一个synchronized方法。这时,不同的对象实例的 synchronized方法是不相干扰的。也就是说,其它线程照样可以同时访问相同类的另一个对象实例中的synchronized方法(这也说明了synchronized的可重入性);
  2. 类锁:某个类的范围,synchronized static staticMethod{}防止多个线程同时访问这个类中的synchronized static 方法。它可以对类的所有对象实例起作用
举个栗子

synchronized使用形式

*********************************************对象锁***************************************
    /**
     * 对象实例中的synchronized方法(普通方法)
     *  锁的时当前对象实例
     */
    public synchronized void method() {
        // Core
    }
    
    /**
     * 对象实例中的synchronized代码块(普通方法)
     * 锁的时括号内的对象实例
     */
    public void method() {
    	// this 当前对象
    	// byte lock = new byte(0); 锁的对象为lock(byte 对象) [创建大小为0 byte对象只需要三行指令码,是创建对象中最经济的]
        synchronized (lock) {
            // Core        
        }
    }
    *******************************************类锁***************************************
    /**
     * 对象实例中的synchronized方法(静态方法)
     *  锁的时当前Class
     */
    public static synchronized void method() {
        // Core
    }

   /**
     * 对象实例中的synchronized代码块(静态方法)
     *  锁的时括号内的Class
     */
     public static void method(){
     	synchronized(MyClass.class){
     		// Core
     	}
     }

ThreadLocal

认识

ThreadLocal,很多地方叫做线程本地变量,也有些地方叫做线程本地存储,其实意思差不多。可能很多朋友都知道ThreadLocal为变量在每个线程中都创建了一个副本,那么每个线程可以访问自己内部的副本变量。

理解

我们来看看源码get()的源码

    /**
     * Returns the value in the current thread's copy of this
     * thread-local variable.  If the variable has no value for the
     * current thread, it is first initialized to the value returned
     * by an invocation of the {@link #initialValue} method.
     *
     * @return the current thread's value of this thread-local
     */
    public T get() {
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null) {
            ThreadLocalMap.Entry e = map.getEntry(this);
            if (e != null) {
                @SuppressWarnings("unchecked")
                T result = (T)e.value;
                return result;
            }
        }
        return setInitialValue();
    }

取得当前线程,然后通过getMap(t)方法获取到一个map,map的类型为ThreadLocalMap。然后接着下面获取到<key,value>键值对,注意这里获取键值对传进去的是 this,而不是当前线程t
如果获取成功,则返回value值。
如果map为空,则调用setInitialValue方法返回value。
看看getMap()方法

    /**
     * Get the map associated with a ThreadLocal. Overridden in
     * InheritableThreadLocal.
     *
     * @param  t the current thread
     * @return the map
     */
    ThreadLocalMap getMap(Thread t) {
        return t.threadLocals;
    }

这里竟然是直接调用的Thread类中的变量 threadLoacls,看看threadLocals的定义

    /* ThreadLocal values pertaining to this thread. This map is maintained
     * by the ThreadLocal class. */
    ThreadLocal.ThreadLocalMap threadLocals = null;

注释翻译:与该线程相关的ThreadLocal值。这个映射由ThreadLocal类维护。
从定义来看threadLocals是ThreadLocal.ThreadLocalMap类型的,那就在来看看这个ThreadLocalMap

    /**
     * ThreadLocalMap is a customized hash map suitable only for
     * maintaining thread local values. No operations are exported
     * outside of the ThreadLocal class. The class is package private to
     * allow declaration of fields in class Thread.  To help deal with
     * very large and long-lived usages, the hash table entries use
     * WeakReferences for keys. However, since reference queues are not
     * used, stale entries are guaranteed to be removed only when
     * the table starts running out of space.
     */
    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;
            }
        }
        ...

ThreadLocalMap是ThreadLocal中的内部类,从它的Entry这个类来看这是一个键值对储存的结构,key的类型为ThreadLocal,值为Object。
我们在回过来看一下setInitialValue()这个方法

    /**
     * Variant of set() to establish initialValue. Used instead
     * of set() in case user has overridden the set() method.
     *
     * @return the initial value
     */
    private T setInitialValue() {
        T value = initialValue();
        Thread t = Thread.currentThread();
        ThreadLocalMap map = getMap(t);
        if (map != null)
            map.set(this, value);
        else
            createMap(t, value);
        return value;
    }

这明显可以看出map是否为空,不为空设置键值,为空就创建Map,看看createMap()

    /**
     * Create the map associated with a ThreadLocal. Overridden in
     * InheritableThreadLocal.
     *
     * @param t the current thread
     * @param firstValue value for the initial entry of the map
     */
    void createMap(Thread t, T firstValue) {
        t.threadLocals = new ThreadLocalMap(this, firstValue);
    }

到这里就应该可以看出来Thread Local创建副本的过程了
首先,我们创建的每个线程Thread类中都存在一个ThreadLocalMap类型的threaLocals变量,这个threadLocal变量就是用来储存我们的变量副本的,当前的ThreadLocal作为键,值 就是我们的变量副本
初始,我们调用get()和 set() 方法会初始化threadLocals变量,以当前ThreadLocal变量为键值,以ThreadLocal要保存的副本变量为value,存到threadLocals。

使用
    // 实例化一个ThreadLocal 线程的本地变量
    static ThreadLocal<Integer> intLocal = new ThreadLocal<Integer>();

    public static void main(String[] args) {
        // 设置初始值
        intLocal.set(1);
        // 得到intLocal的值
        Integer il = intLocal.get();
        // +1并打印出值
        System.out.println(++il);
    }

刚开始上面这个例子运行时发现报了空指针异常:原因是我直接使用get()方法没有使用set()。也就是没有设置初始值。可见ThreadLocal使用时必须要先set() 否则 会报空指针异常,其实不使用set()方法 也可以,就是重写initialValue()方法:

    // 实例化一个ThreadLocal 线程的本地变量
    static ThreadLocal<Integer> intLocal = new ThreadLocal<Integer>(){
        @Override
        protected Integer initialValue(){
            return 1;
        }
    };

    public static void main(String[] args) {
        // 得到intLocal的值
        Integer il = intLocal.get();
        // +1并打印出值
        System.out.println(++il);
    }

Volatile

volatile是一种轻量级的同步机制,它主要有两个特性:一是保证共享变量对所有线程的可见性;二是禁止指令重排序优化。同时需要注意的是,volatile对于单个的共享变量的读/写具有原子性,但是像num++这种复合操作,volatile无法保证其原子性。
具体学习看这里 http://www.cnblogs.com/chengxiao/

猜你喜欢

转载自blog.csdn.net/qq_38345031/article/details/84141100