本篇概述:
使用线程池ExecutorService来管理线程,
具体Executor相关原理可以参考《Think in java》这本书
改动后代码:
/**
* 网络请求入口
* */
public class HttpUtil {
public static void get(String rootUrl, RequestParams params, final LincolnCallBack<JSONObject> callBack) {
rootUrl = UrlUtil.dealGetParams(rootUrl, params);
TaskController taskController = TaskController.registrInstance();
taskController.start(rootUrl,HttpMethod.GET, params, callBack);
}
}
/**
* 线程控制类
*/
public class TaskController {
private static TaskController taskController;
private static ExecutorService executor;
private static int MAX_THREAD_COUNT= 10;
public static TaskController registrInstance(){
if (taskController == null) {
synchronized (TaskController.class) {
if (taskController == null) {
taskController = new TaskController();
executor = Executors.newFixedThreadPool(MAX_THREAD_COUNT);
}
}
}
return taskController;
}
public <T> void start(String rootUrl,HttpMethod method ,RequestParams params,LincolnCallBack<JSONObject> callback){
HttpTask task = new HttpTask(rootUrl,method, callback);
executor.submit(task);
}
}
任务线程类
public class HttpTask implements Runnable{
private String rootUrl;
private LincolnCallBack callBack;
private HttpMethod method;
public HttpTask(String rootUrl,HttpMethod method,LincolnCallBack callback){
this.rootUrl = rootUrl;
this.callBack = callback;
this.method = method;
}
public void sendRequest(){
try {
URL url = new URL(rootUrl);
HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
urlConnection.setRequestMethod(method.toString());
urlConnection.connect();
InputStream inputStream = urlConnection.getInputStream();
ByteArrayOutputStream byteOutSteam = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
int length = -1;
while ((length = inputStream.read(buffer)) != -1) {
byteOutSteam.write(buffer, 0, length);
}
String resultString = byteOutSteam.toString();
JSONObject object = new JSONObject(resultString);
callBack.onSuccess(null, object);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void run() {
sendRequest();
}
}