privatestatic ExecutorService service = Executors.newFixedThreadPool(10); privatestatic SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
publicstaticvoidmain(String[] args){ for (int i = 0; i < 100; i++) { int finalI = i; service.execute(() -> { String date = new ThreadLocalNormalUsage00().date(finalI); System.out.println(date); }); } service.shutdown(); }
public String date(int seconds){ Date date = new Date(seconds); return simpleDateFormat.format(1000 * seconds); } }
privatestatic ExecutorService service = Executors.newFixedThreadPool(10);
publicstaticvoidmain(String[] args){ for (int i = 0; i < 100; i++) { int finalI = i; service.execute(() -> { String date = new ThreadLocalNormalUsage01().date(finalI); System.out.println(date); }); } service.shutdown(); }
public String date(int seconds){ Date date = new Date(seconds); return ThreadSafeFormatter.threadLocal.get().format(1000 * seconds); } }
classService1{ publicvoidprocess(){ User user = new User("test"); UserContextHolder.holder.set(user); System.out.println("service1:" + user.name); new Service2().process(); } }
classService2{ publicvoidprocess(){ User user = UserContextHolder.holder.get(); System.out.println("service2:" + user.name); new Service3().process(); } }
classService3{ publicvoidprocess(){ User user = UserContextHolder.holder.get(); System.out.println("service3:" + user.name); } }
classUserContextHolder{ publicstaticfinal ThreadLocal<User> holder = new ThreadLocal<>(); }
public T get(){ Thread t = Thread.currentThread(); ThreadLocalMap map = getMap(t); if (map != null) { ThreadLocalMap.Entry e = map.getEntry(this); if (e != null) { @SuppressWarnings("unchecked") T result = (T)e.value; return result; } } return setInitialValue(); }