java.util.concurrent.atomic详解

来源:互联网 发布:mysql 缺省时间 编辑:程序博客网 时间:2024/06/05 00:20

1、先看下整体的结构:


2、单词解释:

atomically:原子级的

3、整体解释:

支持在单个变量上解除锁定的线程安全编程包。即使用者无需进行安全的操作,其能自动保证线程安全。

举例1:

AtomicLong:多线程操作AtomicLong对象,提供原子操作的Integer类。每次取得对象的值,并加一(调用其getAndIncrement()方法),运行结果可知其是线程安全的操作。

package Concurrent;import java.util.concurrent.atomic.AtomicLong;public class TestAtomic implements Runnable{        private static final AtomicLong nextSerialNum = new AtomicLong();    @Override    public void run() {        // 直接取得当前值并增长1        System.out.println(Thread.currentThread().getName() + ":" + nextSerialNum.getAndIncrement());        try {            Thread.sleep(100);        } catch (InterruptedException e) {        }    }    public static void main(String[] args) {        TestAtomic st = new TestAtomic();        for (int i = 0; i < 100; i++) {            new Thread(st, "Thread" + i).start();        }        for (int i = 100; i < 200; i++) {            new Thread(st, "Thread" + i).start();        }    }    }
运行结果:截取部分

run:Thread0:0Thread3:3Thread1:1Thread5:5Thread2:2Thread6:6Thread4:4Thread7:7Thread8:8Thread9:9Thread10:10Thread11:11Thread12:12Thread13:13Thread14:14Thread15:15.........Thread192:192Thread193:193Thread194:194Thread195:195Thread196:196Thread197:197Thread198:198Thread199:199
AtomicLong的其他主要方法:

public final long getAndDecrement():减去一操作,和上面的方法一样,返回的值是减操作之前的值。

public final long decrementAndGet():减去一操作,返回的值是减操作之后的值。

举例2:

AtomicBoolean:使用 AtomicBoolean 高效并发处理 “只初始化一次” 的功能要求:

private static AtomicBoolean initialized = new AtomicBoolean(false);public void init(){   if( initialized.compareAndSet(false, true) ){       // 这里放置初始化代码....   }}

compareAndSet(boolean expect, boolean update)解释:

这个方法主要两个作用         

1. 比较AtomicBoolean和expect的值,如果一致,执行方法内的语句。其实就是一个if语句        

2. 把AtomicBoolean的值设成update         

比较最要的是这两件事是一气呵成的,这连个动作之间不会被打断,任何内部或者外部的语句都不可能在两个动作之间运行。

所以其是线程安全的。

普通方式:

public static volatile boolean initialized = false;public void init(){    if( initialized == false ){        initialized = true;        // 这里初始化代码....    }}

举例3:

AtomicReference:使用 AtomicReference 处理引用类型的操作。

package Concurrent;import java.util.concurrent.atomic.AtomicReference;public class TestAtomic{        /**      * 相关方法列表      * @see AtomicReference#compareAndSet(Object, Object) 对比设置值,参数1:原始值,参数2:修改目标引用      * @see AtomicReference#getAndSet(Object) 将引用的目标修改为设置的参数,直到修改成功为止,返回修改前的引用      */      public final static AtomicReference<String>  ATOMIC_REFERENCE = new AtomicReference<>("");            public static void main(String[] args) {          for(int i = 0 ; i < 100 ; i++) {                         new Thread() {                  @Override                public void run() {                      if(ATOMIC_REFERENCE.compareAndSet(ATOMIC_REFERENCE.toString(), ATOMIC_REFERENCE.toString()+"#")) {                          System.out.println(ATOMIC_REFERENCE.toString());                      }                  }              }.start();          }      }  }  
运行结果:截取部分

##############################################################################.......############################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################################

此例子并无实际用处,在此只是为了展示,多线程环境下,使用AtomicReference操作引用类型是线程安全的。

还有其他多个类,在此不一一说明。


1 0
原创粉丝点击