溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

java 中ThreadLocal 的正確用法

發(fā)布時間:2020-09-30 18:00:56 來源:腳本之家 閱讀:190 作者:lqh 欄目:編程語言

java 中ThreadLocal 的正確用法

用法一:在關(guān)聯(lián)數(shù)據(jù)類中創(chuàng)建private static ThreadLocalThreaLocal的JDK文檔中說明:ThreadLocal instances are typically private static fields in classes that wish to associate state with a thread。如果我們希望通過某個類將狀態(tài)(例如用戶ID、事務(wù)ID)與線程關(guān)聯(lián)起來,那么通常在這個類中定義private static類型的ThreadLocal 實例。

例如,在下面的類中,私有靜態(tài) ThreadLocal 實例(serialNum)為調(diào)用該類的靜態(tài) SerialNum.get() 方法的每個線程維護(hù)了一個“序列號”,該方法將返回當(dāng)前線程的序列號。(線程的序列號是在第一次調(diào)用 SerialNum.get() 時分配的,并在后續(xù)調(diào)用中不會更改。)

public class SerialNum { 
  // The next serial number to be assigned 
  private static int nextSerialNum = 0; 
 
  private static ThreadLocal serialNum = new ThreadLocal() { 
    protected synchronized Object initialValue() { 
      return new Integer(nextSerialNum++); 
    } 
  }; 
 
  public static int get() { 
    return ((Integer) (serialNum.get())).intValue(); 
  } 
} 

【例】

public class ThreadContext {
 
 private String userId;
 private Long transactionId;
 
 private static ThreadLocal threadLocal = new ThreadLocal(){
  @Override
    protected ThreadContext initialValue() {
      return new ThreadContext();
    }
 
 };
 public static ThreadContext get() {
  return threadLocal.get();
 }

 public String getUserId() {
  return userId;
 }
 public void setUserId(String userId) {
  this.userId = userId;
 }
 public Long getTransactionId() {
  return transactionId;
 }
 public void setTransactionId(Long transactionId) {
  this.transactionId = transactionId;
 }
 
}

 用法二:在Util類中創(chuàng)建ThreadLocal

這是上面用法的擴(kuò)展,即把ThreadLocal的創(chuàng)建放到工具類中。

【例】例如hibernate的工具類:

public class HibernateUtil {
  private static Log log = LogFactory.getLog(HibernateUtil.class);
  private static final SessionFactory sessionFactory;   //定義SessionFactory
 
  static {
    try {
      // 通過默認(rèn)配置文件hibernate.cfg.xml創(chuàng)建SessionFactory
      sessionFactory = new Configuration().configure().buildSessionFactory();
    } catch (Throwable ex) {
      log.error("初始化SessionFactory失?。?, ex);
      throw new ExceptionInInitializerError(ex);
    }
  }

  //創(chuàng)建線程局部變量session,用來保存Hibernate的Session
  public static final ThreadLocal session = new ThreadLocal();
 
  /**
   * 獲取當(dāng)前線程中的Session
   * @return Session
   * @throws HibernateException
   */
  public static Session currentSession() throws HibernateException {
    Session s = (Session) session.get();
    // 如果Session還沒有打開,則新開一個Session
    if (s == null) {
      s = sessionFactory.openSession();
      session.set(s);     //將新開的Session保存到線程局部變量中
    }
    return s;
  }
 
  public static void closeSession() throws HibernateException {
    //獲取線程局部變量,并強(qiáng)制轉(zhuǎn)換為Session類型
    Session s = (Session) session.get();
    session.set(null);
    if (s != null)
      s.close();
  }
}

用法三:在Runnable中創(chuàng)建ThreadLocal

 還有一種用法是在線程類內(nèi)部創(chuàng)建ThreadLocal,基本步驟如下:

1、在多線程的類(如ThreadDemo類)中,創(chuàng)建一個ThreadLocal對象threadXxx,用來保存線程間需要隔離處理的對象xxx。

2、在ThreadDemo類中,創(chuàng)建一個獲取要隔離訪問的數(shù)據(jù)的方法getXxx(),在方法中判斷,若ThreadLocal對象為null時候,應(yīng)該new()一個隔離訪問類型的對象,并強(qiáng)制轉(zhuǎn)換為要應(yīng)用的類型。

3、在ThreadDemo類的run()方法中,通過調(diào)用getXxx()方法獲取要操作的數(shù)據(jù),這樣可以保證每個線程對應(yīng)一個數(shù)據(jù)對象,在任何時刻都操作的是這個對象。 

public class ThreadLocalTest implements Runnable{
  
  ThreadLocal<Studen> studenThreadLocal = new ThreadLocal<Studen>();

  @Override
  public void run() {
    String currentThreadName = Thread.currentThread().getName();
    System.out.println(currentThreadName + " is running...");
    Random random = new Random();
    int age = random.nextInt(100);
    System.out.println(currentThreadName + " is set age: " + age);
    Studen studen = getStudent(); //通過這個方法,為每個線程都獨立的new一個student對象,每個線程的的student對象都可以設(shè)置不同的值
    studen.setAge(age);
    System.out.println(currentThreadName + " is first get age: " + studen.getAge());
    try {
      Thread.sleep(500);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
    System.out.println( currentThreadName + " is second get age: " + studen.getAge());
    
  }
  
  private Studen getStudent() {
    Studen studen = studenThreadLocal.get();
    if (null == studen) {
      studen = new Studen();
      studenThreadLocal.set(studen);
    }
    return studen;
  }

  public static void main(String[] args) {
    ThreadLocalTest t = new ThreadLocalTest();
    Thread t1 = new Thread(t,"Thread A");
    Thread t2 = new Thread(t,"Thread B");
    t1.start();
    t2.start();
  }
  
}

class Studen{
  int age;
  public int getAge() {
    return age;
  }
  public void setAge(int age) {
    this.age = age;
  }
  
}

感謝閱讀,希望能幫助到大家,謝謝大家對本站的支持!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI