import java.util.concurrent.ConcurrentHashMap; import java.util.concurrent.TimeUnit; import java.util.stream.IntStream;public class Test {public static void main(String[] args){ThreadLocalExample.test();} }/*21.2 线程上下文设计*/class ApplicationConfiguration {} class RuntimeInfo {} class ActionContext {}final class ApplicationContext{private ApplicationConfiguration configuration;private RuntimeInfo runtimeInfo;//。。。private static class Holder{private static ApplicationContext instance = new ApplicationContext();}public static ApplicationContext getContext() {return Holder.instance;}public ApplicationConfiguration getConfiguration() {return configuration;}public void setConfiguration(ApplicationConfiguration configuration) {this.configuration = configuration;}public RuntimeInfo getRuntimeInfo() {return runtimeInfo;}public void setRuntimeInfo(RuntimeInfo runtimeInfo) {this.runtimeInfo = runtimeInfo;}/*需求:单个线程执行的步骤会非常多,后一个步骤的输入可能是前一个步骤的输出,比如单个线程多步骤执行时,为了使得功能单一,有时候我们会采用职责链设计模式。虽然有时候后一个步骤未必需要前一个步骤的输出结果,但是都需要将context从头到尾进行传递,假如方法参数比较少还可以容忍,如果方法参数比较多,在七八次的调用甚至十几次的调用,都需要从头到尾地传递context,很显然这是一种比较繁琐的设计,我们可以采用上下文设计来解决这样的问题。*/private ConcurrentHashMapcontexts =new ConcurrentHashMap<>();public ActionContext getContexts() {ActionContext actionContext = contexts.get(Thread.currentThread());if(actionContext==null){actionContext=new ActionContext();contexts.put(Thread.currentThread(),actionContext);}return actionContext;} }/*21.3.2 ThreadLocal的方法详解及源码分析*/ class ThreadLocalExample{public static void test() {ThreadLocal l = new ThreadLocal<>();IntStream.range(0, 10).forEach(i->new Thread(()->{try{l.set(i);System.out.println(Thread.currentThread()+ " set i "+l.get());TimeUnit.SECONDS.sleep(1);System.out.println(Thread.currentThread()+ " set i "+l.get());} catch (InterruptedException e) {e.printStackTrace();}}).start());try {TimeUnit.SECONDS.sleep(3);System.out.println(l.get());} catch (InterruptedException e) {e.printStackTrace();}} }
《Java高并发编程详解》笔记