ThreadLocal範例

import java.util.Random;

/**
 *
 */

/**
 * @author Oct 19, 2009
 * @createDate 2:01:42 PM
 */
public class ThreadLocalTest {

 private static ThreadLocal<forIn> seqNum = new ThreadLocal<forIn>() ;

 public ThreadLocal getLoc(){
  return seqNum;
 }
 
 public void setNum(Integer value) {
  if (seqNum.get()==null)
   seqNum.set(new forIn());
  seqNum.get().setValue(value);
  //return seqNum.get();
 }
 
 public int getNum() {
  //seqNum.set(seqNum.get() + 1);
  return seqNum.get().getValue();
 }
 
 public static void main(String[] args) {
  ThreadLocalTest sn = new ThreadLocalTest();
  // ③ 3個線程共享sn,各自產生一個forIn對象
  TestClient t1 = new TestClient(sn);
  TestClient t2 = new TestClient(sn);
  TestClient t3 = new TestClient(sn);
  t1.start();
  t2.start();
  t3.start();
 }

 private static class TestClient extends Thread {
  private ThreadLocalTest sn;
  public TestClient(ThreadLocalTest sn) {
   this.sn = sn;
  }
  public void run() {
   for (int i = 0; i < 3; i++) {// ④每個線程打出3個序列值
    Random random = new Random();  
          int age = random.nextInt(100);  
    sn.setNum(age);
    System.out.println("thread[" + Thread.currentThread().getName()
      + "] sn[" + sn.getNum() + "]" + sn.getLoc().get());
   }
  }
 }
 
 private class forIn {
  private Integer value;

  public forIn() {
   value = 0;
  }

  public Integer getValue() {
   return value;
  }

  public void setValue(Integer value) {
   this.value = value;
  }

 }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章