WEB开发网
开发学院软件开发Java 多线程基础总结五--atomic 阅读

多线程基础总结五--atomic

 2010-01-22 00:00:00 来源:WEB开发网   
核心提示: JDK5以后在java.util.concurrent.atomic包下提供了十几个原子类,常见的是 AtomicInteger,AtomicLong,AtomicReference以及它们的数组形式,多线程基础总结五--atomic(2),还有AtomicBoolean和为了处理 ABA问题引

JDK5以后在java.util.concurrent.atomic包下提供了十几个原子类。常见的是 AtomicInteger,AtomicLong,AtomicReference以及它们的数组形式,还有AtomicBoolean和为了处理 ABA问题引入的AtomicStampedReference类,最后就是基于反射的对volatile变量进行更新的实用工具类:AtomicIntegerFieldUpdater,AtomicLongFieldUpdater,AtomicReferenceFieldUpdater。这些原子类理论上能够大幅的提升性能。并且java.util.concurrent内的并发集合,线程池,执行器,同步器的内部实现大量的依赖这些无锁原子类,从而争取性能的最大化。下面通过一个简单的例子看看:

Java代码

import java.util.concurrent.atomic.AtomicIntegerFieldUpdater; 
import java.util.concurrent.atomic.AtomicInteger; 
 
/** 
 * User: yanxuxin 
 * Date: Dec 16, 2009 
 * Time: 10:49:40 PM 
 */ 
public class AtomicCounterSample extends Thread { 
  private AtomicCounter atomicCounter; 
 
  public AtomicCounterSample(AtomicCounter atomicCounter) { 
    this.atomicCounter = atomicCounter; 
  } 
 
  @Override 
  public void run() { 
    long sleepTime = (long) (Math.random() * 100); 
    try { 
      Thread.sleep(sleepTime); 
    } catch (InterruptedException e) { 
      e.printStackTrace(); 
    } 
 
    atomicCounter.counterIncrement(); 
  } 
 
  public static void main(String[] args) throws Exception { 
    AtomicCounter atomicCounter = new AtomicCounter(); 
 
    for (int i = 0; i < 5000; i++) { 
      new AtomicCounterSample(atomicCounter).start(); 
    } 
 
    Thread.sleep(3000); 
 
    System.out.println("counter=" + atomicCounter.getCounter()); 
  } 
} 
 
class AtomicCounter { 
  private AtomicInteger counter = new AtomicInteger(0); 
 
  public int getCounter() { 
    return counter.get(); 
  } 
 
  public void counterIncrement() { 
    for (; ;) { 
      int current = counter.get(); 
      int next = current + 1; 
      if (counter.compareAndSet(current, next)) 
        return; 
    } 
  } 
} 
 
class AtomicCounter2 { 
  private volatile int counter; 
  private static final AtomicIntegerFieldUpdater<AtomicCounter2> counterUpdater = AtomicIntegerFieldUpdater.newUpdater(AtomicCounter2.class, "counter"); 
 
  public int getCounter() { 
    return counter; 
  } 
 
  public int counterIncrement() { 
//    return counter++; 
    return counterUpdater.getAndIncrement(this); 
  } 
}

Tags:线程 基础 总结

编辑录入:爽爽 [复制链接] [打 印]
赞助商链接