多线程FutureTask

package com.wt.thread;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.client.RestTemplate;

public class RomoteProcedureCall {

    @Autowired
    private RestTemplate  restTemplate;//spring提供的一个远程调用工具

    /**
     * 调用获取用户基本信息的http接口
     * @param userId
     * @return
     */
    public JSONObject getUserInfo(String userId){

        //先调用获取用户基本信息的http接口
        long userInfoTime=System.currentTimeMillis();
        String value=restTemplate.getForObject("http://www.tony.com/userinfo/get?userId="+userId,String.class);
        JSONObject userInfo=JSONObject.parseObject(value);
        System.out.println("userInfo-api用户基本信息接口调用时间为"+(System.currentTimeMillis()-userInfoTime));
        return userInfo;
    }

    /**
     * 获取用户积分信息的接口
     *
     * @param userId
     * @return
     */
    public JSONObject getIntergrallinfo(String userId){
        //调用获取用户积分信息的接口
        long intergralApiTime=System.currentTimeMillis();
        String intergral=restTemplate.getForObject("http://www.tony.com/userinfo/get?userId="+userId,String.class);
        JSONObject userInfo=JSONObject.parseObject(intergral);
        System.out.println("intergral-api积分接口调用时间为"+(System.currentTimeMillis()-intergralApiTime));
        return userInfo;
    };
}
package com.wt.thread;

import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.concurrent.*;

public class UserService {

    @Autowired
    RomoteProcedureCall romoteProcedureCall;

    //线程池公用
    ScheduledExecutorService scheduledExecutorService=Executors.newScheduledThreadPool(10);
    /*
    查询多个系统的数据,合并返回
     */
    public Object getUserInfo(String userId)throws ExecutionException,InterruptedException{

        //多线程异步执行,结果怎么获取?  ----JDK  java开发工具包
        //专门针对异步编程  Future/Callable --Api
        GivenFutureTask<JSONObject> userInfofutureTask=new GivenFutureTask(new Callable<JSONObject>() {
            @Override
            public JSONObject call() throws Exception {
                //1. 用户基本信息获取
                JSONObject userInfo=romoteProcedureCall.getUserInfo(userId);
                return userInfo;
            }
        });

        GivenFutureTask<JSONObject> intergralFutureTask=new GivenFutureTask(()-> {
                //1. 用户基本信息获取
                JSONObject intergrallinfo=romoteProcedureCall.getIntergrallinfo(userId);
                return intergrallinfo;
        });
        new Thread(userInfofutureTask).start();//把任务交给线程运行
        new Thread(intergralFutureTask).start();//把任务交给线程运行
       /* new Thread(new Runnable() {
            @Override
            public void run() {
                //T0D0 业务代码
                //1. 用户基本信息获取
                JSONObject userInfo=romoteProcedureCall.getUserInfo(userId);//3秒优化
            }
        }).start();*/

        //1. 用户基本信息获取
        //JSONObject userInfo=romoteProcedureCall.getUserInfo(userId);//3秒优化
        //2. 积分信息接口获取
        //JSONObject intergrallinfo=romoteProcedureCall.getIntergrallinfo(userId);//2秒
        //3. 数据汇总
        JSONObject result=new JSONObject();
        result.putAll(userInfofutureTask.get());//get方法返回执行结果,如果线程还没执行完毕,就会等待执行结果返回。
        result.putAll(intergralFutureTask.get());


        return result;
    }
}
package com.wt.thread;

import java.util.concurrent.Callable;

//目标:替换JDK的FutureTask,验证过程
//已知推理未知
public class GivenFutureTask<T> implements Runnable{

    Callable<T> callable;//包装-任务执行的逻辑
    T result;//callable执行结果
    volatile String state="NEW";
    public GivenFutureTask(Callable callable){
        this.callable=callable;
    }

    @Override
    public void run() {//请求接口的线程
        //线程执行 --run
        try {
            callable.call();
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            state="END";
        }
        //执行结束,已经有结果,所有等待结果的线程唤醒
        synchronized (this){
            this.notifyAll();
        }

    }

    //等待任务执行结束再返回结果
    public T get() throws InterruptedException {
        //如果没有执行结束
        if("END".equals(state)){
            return result;
        }
        while (!"END".equals(state)){
        //进入等待--线程不在继续执行
            synchronized (this){
                this.wait();
            }
        }
       return result;// 返回任务task执行结果(callable)
    }


}
package com.wt.thread;

public interface GivenCallable<V> {

    /**
     * Computes a result, or throws an exception if unable to do so.
     *
     * @return computed result
     * @throws Exception if unable to compute a result
     */
    V call() throws Exception;

}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值