ThreadLocal是救火队长
生活随笔
收集整理的這篇文章主要介紹了
ThreadLocal是救火队长
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
package threadlocal;import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;/*** 描述: 利用ThreadLocal,給每個線程分配自己的dateFormat對象,保證了線程安全,高效利用內存*/
public class ThreadLocalNormalUsage05 {public static ExecutorService threadPool = Executors.newFixedThreadPool(10);public static void main(String[] args) throws InterruptedException {for (int i = 0; i < 1000; i++) {int finalI = i;threadPool.submit(new Runnable() {@Overridepublic void run() {String date = new ThreadLocalNormalUsage05().date(finalI);System.out.println(date);}});}threadPool.shutdown();}public String date(int seconds) {//參數的單位是毫秒,從1970.1.1 00:00:00 GMT計時Date date = new Date(1000 * seconds);
// SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");SimpleDateFormat dateFormat = ThreadSafeFormatter.dateFormatThreadLocal2.get();return dateFormat.format(date);}
}class ThreadSafeFormatter {public static ThreadLocal<SimpleDateFormat> dateFormatThreadLocal = new ThreadLocal<SimpleDateFormat>() {@Overrideprotected SimpleDateFormat initialValue() {return new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");}};public static ThreadLocal<SimpleDateFormat> dateFormatThreadLocal2 = ThreadLocal.withInitial(() -> new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"));
}
?
總結
以上是生活随笔為你收集整理的ThreadLocal是救火队长的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 走过的弯路,你的套路
- 下一篇: 悔不当初:回顾进化之路