梦幻之旅

DEBUG - 天道酬勤

   :: 首页 :: 新随笔 :: 联系 :: 聚合  :: 管理 ::
  671 随笔 :: 6 文章 :: 256 评论 :: 0 Trackbacks

public class Sequence {
 private static ThreadLocal<Integer> localVar = new ThreadLocal<Integer>() {
  public Integer initialValue() {
   return 0;
  }
 };

 public int getNextVal() {
  localVar.set(localVar.get() + 1);
  return localVar.get();
 }

 public static void main(String[] args) {
  Sequence seq = new Sequence();
  Client client1 = new Client(seq);
  Client client2 = new Client(seq);
  Client client3 = new Client(seq);

  client1.start();
  client2.start();
  client3.start();

 }

}


package hvp.spring.transaction.threadLocal;

public class Client extends Thread{
 private Sequence seq;
 public Client(Sequence seq){
  this.seq = seq;
 }
 public void run(){
  StringBuffer sb = new StringBuffer();
  for(int i=0;i<5;i++){
   sb.append("Thread[");
   sb.append(Thread.currentThread().getName());
   sb.append("] seq[");
   sb.append(seq.getNextVal());
   sb.append("]");
   System.out.println(sb.toString());
   sb.delete(0, sb.length());
  }
 }
}


posted on 2008-08-02 23:26 HUIKK 阅读(367) 评论(0)  编辑  收藏 所属分类: Hibernate

只有注册用户登录后才能发表评论。


网站导航: