【详解】上下文设计模式

分析

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

上下文实现

  • 先设计一个上下文,负责在线程执行的过程中传递结果
  • 模拟两个方法,第一个方法从数据库拿名字第二个方法根据第一个方法拿出的名字返回身份证号
  • 设计线程的执行方法,在执行时,创建一个唯一的上下文进行传递参数
/**
 * 上下文
 */
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());
    }
}

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

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值