一区二区三区在线-一区二区三区亚洲视频-一区二区三区亚洲-一区二区三区午夜-一区二区三区四区在线视频-一区二区三区四区在线免费观看

服務器之家:專注于服務器技術及軟件下載分享
分類導航

PHP教程|ASP.NET教程|JAVA教程|ASP教程|

服務器之家 - 編程語言 - JAVA教程 - Java ThreadLocal 線程安全問題解決方案

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

2020-06-19 11:35夏中偉 JAVA教程

這篇文章主要介紹了Java ThreadLocal 線程安全問題解決方案的相關資料,需要的朋友可以參考下

一、線程安全問題產生的原因

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

二、線程安全問題

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

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

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

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

使用ThreadLocal解決線程安全:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
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解決方案:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
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);
    }
  }
}

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

延伸 · 閱讀

精彩推薦
主站蜘蛛池模板: 楚乔传第二部全60集免费观看 | 青草午夜精品视频在线观看 | 免费观看视频高清在线 | 91国内精品线免费播放 | 免费真实播放国产乱子伦 | 国产精品第一 | 羞羞漫画视频 | 国产情侣偷国语对白 | 3d动漫美女被吸乳羞羞有 | 多人群p全肉小说 | 欧美三级小说 | 成人免费观看在线视频 | 亚洲第一男人天堂 | 欧美老骚 | 九九在线免费视频 | 久久久无码精品亚洲欧美 | 国产亚洲毛片在线 | 欧美无专区| 精精国产xxxx视频在线播放器 | 日本护士撒尿xxxx欧美 | porno日本大学生高清 | 精品亚洲一区二区三区在线播放 | 欧美一区二区三区免费不卡 | 国产91精品久久久久久久 | 国产成人亚洲综合91精品555 | 免费一级毛片完整版在线看 | 成人免费视频一区二区三区 | 草草免费观看视频在线 | 红楼影视h38bar在线线播放 | 香蕉精品 | 亚洲国产精品久久久久久 | 国产小视频在线免费观看 | 亚洲swag精品自拍一区 | 色色色色色色网 | 校花在公车上被内射好舒服 | 男人的天堂视频在线 | 1314酒色| 国产精品一区二区久久 | 亚洲嫩模吧粉嫩粉嫩冒白浆 | 婷婷色在线 | 2022超帅男同gayxxx |