Java多線程編程中使用DateFormat類_java

來源:互聯網
上載者:User

 DateFormat 類是一個非安全執行緒的類。javadocs 文檔裡面提到"Date formats是不能同步的。 我們建議為每個線程建立獨立的日期格式。 如果多個線程同時訪問一個日期格式,這需要在外部加上同步代碼塊。"

以下的代碼為我們展示了如何在一個線程環境裡面使用DateFormat把字串日期轉換為日期對象。建立一個執行個體來擷取日期格式會比較高效,因為系統不需要多次擷取本地語言和國家。
 

public class DateFormatTest {  private final DateFormat format =      new SimpleDateFormat("yyyyMMdd");  public Date convert(String source)           throws ParseException{  Date d = format.parse(source);  return d; }}

這段代碼是非安全執行緒的。我們可以通過在多個線程中調用它。在以下調用的代碼中,我建立了一個有兩個線程的線程池,並提交了5個日期轉換任務,之後查看運行結果:
 

final DateFormatTest t =new DateFormatTest();Callable<Date> task =new Callable<Date>(){  public Date call()throws Exception {    return t.convert("20100811");  }}; //讓我們嘗試2個線程的情況ExecutorService exec = Executors.newFixedThreadPool(2);List<Future<Date>> results =       new ArrayList<Future<Date>>(); //實現5次日期轉換for(int i =0; i <5; i++){  results.add(exec.submit(task));}exec.shutdown(); //查看結果for(Future<Date> result : results){  System.out.println(result.get());}

代碼的運行結果並非如我們所願 - 有時候,它輸出正確的日期,有時候會輸出錯誤的(例如.Sat Jul 31 00:00:00 BST 2012),有些時候甚至會拋出NumberFormatException!


如何並發使用DateFormat類

我們可以有多種方法線上程安全的情況下使用DateFormat類。

1. 同步

最簡單的方法就是在做日期轉換之前,為DateFormat對象加鎖。這種方法使得一次只能讓一個線程訪問DateFormat對象,而其他線程只能等待。
 

public Date convert(String source)          throws ParseException{ synchronized(format) {  Date d = format.parse(source);  return d; }}


2. 使用ThreadLocal

另外一個方法就是使用ThreadLocal變數去容納DateFormat對象,也就是說每個線程都有一個屬於自己的副本,並無需等待其他線程去釋放它。這種方法會比使用同步塊更高效。
 

public class DateFormatTest {  private static final ThreadLocal<DateFormat> df         = new ThreadLocal<DateFormat>(){  @Override  protected DateFormat initialValue() {    return new SimpleDateFormat("yyyyMMdd");  } };  public Date convert(String source)           throws ParseException{  Date d = df.get().parse(source);  return d; }}

3. Joda-Time

Joda-Time 是一個很棒的開源的 JDK 的日期和日曆 API 的替代品,其 DateTimeFormat 是安全執行緒而且不變的。

 

import org.joda.time.DateTime;import org.joda.time.format.DateTimeFormat;import org.joda.time.format.DateTimeFormatter;import java.util.Date; public class DateFormatTest {  private final DateTimeFormatter fmt =    DateTimeFormat.forPattern("yyyyMMdd");  public Date convert(String source){  DateTime d = fmt.parseDateTime(source);  returnd.toDate(); }}


聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.