国产探花免费观看_亚洲丰满少妇自慰呻吟_97日韩有码在线_资源在线日韩欧美_一区二区精品毛片,辰东完美世界有声小说,欢乐颂第一季,yy玄幻小说排行榜完本

首頁 > 編程 > Java > 正文

Java ThreadLocal 線程安全問題解決方案

2019-11-26 13:46:12
字體:
供稿:網(wǎng)友

一、線程安全問題產(chǎn)生的原因

線程安全問題都是由全局變量及靜態(tài)變量引起的

二、線程安全問題

SimpleDateFormate sdf = new SimpleDateFormat();使用sdf.parse(dateStr);sdf.format(date);在sdf內(nèi)有一個對Caleadar對象的引用,在源碼sdf.parse(dateStr);源碼中calendar.clear();和calendar.getTime(); // 獲取calendar的時間

如果 線程A 調(diào)用了 sdf.parse(), 并且進行了 calendar.clear()后還未執(zhí)行calendar.getTime()的時候,線程B又調(diào)用了sdf.parse(), 這時候線程B也執(zhí)行了sdf.clear()方法, 這樣就導致線程A的的calendar數(shù)據(jù)被清空了;

ThreadLocal是使用空間換時間,synchronized是使用時間換空間

使用ThreadLocal解決線程安全:

public class ThreadLocalDateUtil {  private static final String date_format = "yyyy-MM-dd HH:mm:ss";  private static ThreadLocal<DateFormat> threadLocal = new ThreadLocal<DateFormat>();   public static DateFormat getDateFormat()   {     DateFormat df = threadLocal.get();     if(df==null){       df = new SimpleDateFormat(date_format);       threadLocal.set(df);     }     return df;   }   public static String formatDate(Date date) throws ParseException {    return getDateFormat().format(date);  }  public static Date parse(String strDate) throws ParseException {    return getDateFormat().parse(strDate);  } }

使用synchronized解決方案:

public class DateSyncUtil {  private static SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");      public static String formatDate(Date date)throws ParseException{    synchronized(sdf){      return sdf.format(date);    }   }     public static Date parse(String strDate) throws ParseException{    synchronized(sdf){      return sdf.parse(strDate);    }  }}

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

發(fā)表評論 共有條評論
用戶名: 密碼:
驗證碼: 匿名發(fā)表
主站蜘蛛池模板: 长乐市| 惠安县| 张家港市| 关岭| 射阳县| 永平县| 株洲县| 巴南区| 隆德县| 武清区| 临潭县| 志丹县| 正蓝旗| 太原市| 江山市| 大同市| 莱阳市| 绥中县| 玉溪市| 临漳县| 余姚市| 榆林市| 新乐市| 新绛县| 桐乡市| 沈丘县| 上思县| 延安市| 元朗区| 新竹市| 保靖县| 南安市| 台南县| 垦利县| 元江| 临沭县| 安多县| 喀什市| 平定县| 右玉县| 合川市|