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

多线程基础总结四--ThreadLocal

 2010-01-22 00:00:00 来源:WEB开发网   
核心提示: 再看ThreadLocal和synchronized的本质,前者不在乎多占点空间,多线程基础总结四--ThreadLocal(2),但是绝对的忍受不了等待;后者对等待无所谓,但是就是不喜欢浪费空间,下面写个简单的例子解释一下,不过个人觉得设计的例子不太好,这也反映出了算法的一个规律:通常是使用场

再看ThreadLocal和synchronized的本质。前者不在乎多占点空间,但是绝对的忍受不了等待;后者对等待无所谓,但是就是不喜欢浪费空间。这也反映出了算法的一个规律:通常是使用场景决定时间和空间的比例,既省时又省地的算法多数情况下只存在于幻想之中。下面写个简单的例子解释一下,不过个人觉得设计的例子不太好,以后有实际的启发再替换吧。

Java代码

import java.util.concurrent.atomic.AtomicInteger; 
 
/** 
 * User: yanxuxin 
 * Date: Dec 14, 2009 
 * Time: 9:26:41 PM 
 */ 
public class ThreadLocalSample extends Thread { 
  private OperationSample2 operationSample; 
 
  public ThreadLocalSample(OperationSample2 operationSample) { 
    this.operationSample = operationSample; 
  } 
 
  @Override 
  public void run() { 
    operationSample.printAndIncrementNum(); 
  } 
 
  public static void main(String[] args) { 
 
    final OperationSample2 operation = new OperationSample2();//The shared Object for threads. 
 
    for (int i = 0; i < 5; i++) { 
      new ThreadLocalSample(operation).start(); 
    } 
  } 
} 
 
class OperationSample { 
  private int num; 
 
  //public synchronized void printAndIncrementNum() { 
  public void printAndIncrementNum() { 
    for (int i = 0; i < 2; i++) { 
      System.out.println(Thread.currentThread().getName() + "[id=" + num + "]"); 
      num += 10; 
    } 
  } 
} 
 
class OperationSample2 { 
 
  private static ThreadLocal<Integer> threadArg = new ThreadLocal<Integer>() { 
    @Override 
    protected Integer initialValue() { 
      return 0; 
    } 
  }; 
 
  public void printAndIncrementNum() { 
    for (int i = 0; i < 2; i++) { 
      int num = threadArg.get(); 
      threadArg.set(num + 10); 
      System.out.println(Thread.currentThread().getName() + "[id=" + num + "]"); 
    } 
  } 
} 
 
class OperationSample3 { 
 
  private static final AtomicInteger uniqueId = new AtomicInteger(0); 
  private static ThreadLocal<Integer> threadArg = new ThreadLocal<Integer>() { 
    @Override 
    protected Integer initialValue() { 
      return uniqueId.getAndIncrement(); 
    } 
  }; 
 
  public void printAndIncrementNum() { 
    for (int i = 0; i < 2; i++) { 
      int num = threadArg.get(); 
      threadArg.set(num + 10); 
      System.out.println(Thread.currentThread().getName() + "[id=" + num + "]"); 
    } 
  } 
}

Tags:线程 基础 总结

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