【详解】上下文设计模式

分析

  • 线程在执行过程中可能分了多个阶段
  • 后一个方法可能需要用到前一个阶段的结果
  • 通过设置一个上下文,每执行一个方法,将结果放入到上下文中,下一个方法的调用时,会调取上下文中的结果继续执行
  • 这个上下文是在一个线程内部是单例的

上下文实现

  • 先设计一个上下文,负责在线程执行的过程中传递结果
  • 模拟两个方法,第一个方法从数据库拿名字第二个方法根据第一个方法拿出的名字返回身份证号
  • 设计线程的执行方法,在执行时,创建一个唯一的上下文进行传递参数
/** * 上下文 */
public class Context {
    private String name;
    private String cardId;

    public void setName(String name) {
        this.name = name;
    }

    public String getName() {
        return name;
    }

    public void setCardId(String cardId) {
        this.cardId = cardId;
    }


    public String getCardId() {
        return cardId;
    }
}
/** * 模拟从数据库拿数据 */
public class QueryFromDBAction {

    public void excecute(Context context){
        try {
            Thread.sleep(1000);
            String name = "Alex" + Thread.currentThread().getName();
            context.setName(name);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
/** * 获取身份证号 */
public class QueryFromHttpAction {
    public void excecute(Context context){
        String name = context.getName();
        String cardId = getCardId(name);
        context.setCardId(cardId);
    }

    private String getCardId(String name){
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "146433131" + Thread.currentThread().getId();
    }
}
public class ExecutionTask implements Runnable {

    private QueryFromDBAction queryAction = new QueryFromDBAction();

    private QueryFromHttpAction httpAction = new QueryFromHttpAction();

    @Override
    public void run() {
        final Context context =new Context();
        queryAction.excecute(context);
        httpAction.excecute(context);
        System.out.println("用户的名字为"+ context.getName() + " ,身份证号是"+context.getCardId());
    }
}
public class ContextTest {
    public static void main(String[] args) {

        IntStream.range(1,5).forEach(i->{
            new Thread(new ExecutionTask()).start();
        });
    }
}
  • 这个方法将上下文显示的定义到参数中传递,可以继续利用ThreadLocal方法优化

使用ThreadLocal实现

基本思路是

  • 每个线程从同一个ThreadLocal中取出context进行数据的传递
  • 每一个线程取出的context是线程隔离的,不会被其他线程修改,所以是线程安全的
  • 为了保证每个线程都是从同一个ThreadLocal中取出context,设计一个单例,里面保存一个唯一的ThreadLocal
  • 设计一个默认值,在第一次获取时,默认构造一个context供外界修改
public class ActionContext {

    private static final ThreadLocal<Context> THREAD_LOCAL = new ThreadLocal<Context>(){
        @Override
        protected Context initialValue() {
            return new Context();
        }
    };

    private static class ContextHolder{
        private final static ActionContext ACTION_CONTEXT = new ActionContext();
    }

    public static ActionContext getInstance(){
        return ContextHolder.ACTION_CONTEXT;
    }

    public Context getContext(){
        return THREAD_LOCAL.get();
    }
}
/** * 获取身份证号 */
public class QueryFromHttpAction {
    public void excecute(){
        Context context = ActionContext.getInstance().getContext();
        String cardId = getCardId(context.getName());
        context.setCardId(cardId);
    }

    private String getCardId(String name){
        try {
            Thread.sleep(1000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        return "146433131" + Thread.currentThread().getId();
    }
}
/** * 模拟从数据库拿数据 */
public class QueryFromDBAction {

    public void excecute( ){
        try {
            Thread.sleep(1000);
            String name = "Alex" + Thread.currentThread().getName();
            ActionContext.getInstance().getContext().setName(name);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}
public class ExecutionTask implements Runnable {

    private QueryFromDBAction queryAction = new QueryFromDBAction();

    private QueryFromHttpAction httpAction = new QueryFromHttpAction();

    @Override
    public void run() {        
        queryAction.excecute();
        httpAction.excecute();
        Context context =ActionContext.getInstance().getContext();
        System.out.println("用户的名字为"+ context.getName() + " ,身份证号是"+context.getCardId());
    }
}

注意:<mark>线程池中如果使用该设计模式,需要先清理掉上一次执行的Context</mark>

全部评论

相关推荐

点赞 评论 收藏
分享
06-13 17:33
门头沟学院 Java
顺序不记了,大致顺序是这样的,有的相同知识点写分开了1.基本数据类型2.基本数据类型和包装类型的区别3.==和equals区别4.ArrayList与LinkedList区别5.hashmap底层原理,put操作时会发生什么6.说出几种树型数据结构7.B树和B+树区别8.jvm加载类机制9.线程池核心参数10.创建线程池的几种方式11.callable与runnable区别12.线程池怎么回收线程13.redis三剑客14.布隆过滤器原理,不要背八股,说说真正使用时遇到了问题没有(我说没有,不知道该怎么回答了)15.堆的内存结构16.自己在写项目时有没有遇见过oom,如何处理,不要背八股,根据真实经验,我说不会17.redis死锁怎么办,watchdog机制如何发现是否锁过期18.如何避免redis红锁19.一个表性别与年龄如何加索引20.自己的项目的QPS怎么测的,有没有真正遇到大数量表21.说一说泛型22.springboot自动装配原理23.springmvc与springboot区别24.aop使用过嘛?动态代理与静态代理区别25.spring循环依赖怎么解决26.你说用过es,es如何分片,怎么存的数据,1000万条数据怎么写入库中27.你说用limit,那么在数据量大之后,如何优化28.rabbitmq如何批次发送,批量读取,答了延迟队列和线程池,都不对29.计网知不知道smtp协议,不知道写了对不对,完全听懵了30.springcloud知道嘛?只是了解反问1.做什么的?短信服务,信息量能到千万级2.对我的建议,基础不错,但是不要只背八股,多去实际开发中理解。面试官人不错,虽然没露脸,但是中间会引导我回答问题,不会的也只是说对我要求没那么高。面完问我在济宁生活有没有困难,最快什么时候到,让人事给我聊薪资了。下午人事打电话,问我27届的会不会跑路,还在想办法如何使我不跑路,不想扣我薪资等。之后我再联系吧,还挺想去的😭,我真不跑路哥😢附一张河科大幽默大专图,科大就是大专罢了
查看30道真题和解析
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务