创建一个单例:
package com.caiqr.mock.cp.thread;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.*;
/**
* Created by tangxuelong on 16-11-22.
*/
public class ThreadPool {
private static ScheduledExecutorService executor = Executors.newScheduledThreadPool(50);
private static ThreadPool instance = new ThreadPool();
private ThreadPool() {
}
public static ThreadPool getInstance() {
return instance;
}
public ScheduledExecutorService getExecutor() {
return executor;
}
}
创建一个执行任务继承Runable
package com.caiqr.mock.cp.thread;
import com.caiqr.mock.cp.HeCaiWsdl.Md5Util;
import com.caiqr.mock.cp.constant.BjBiyingConstant;
import org.springframework.http.HttpMethod;
import org.springframework.http.client.ClientHttpRequest;
import org.springframework.http.client.ClientHttpResponse;
import org.springframework.http.client.SimpleClientHttpRequestFactory;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
/**
* Created by tangxuelong on 16-11-21.
*/
public class BjSendNotifyTicket implements Runnable {
private String paramsStr;
public BjSendNotifyTicket(String paramsStr) {
this.paramsStr = paramsStr;
}
private Integer resendCount = 0;
@Override
public void run() {
try {
System.out.println("start http request");
System.out.println("params is" + paramsStr);
URI uri = new URI(BjBiyingConstant.NOTIFY_TICKET_URL + "?printresualt=" + paramsStr);
SimpleClientHttpRequestFactory schr = new SimpleClientHttpRequestFactory();
ClientHttpRequest chr = schr.createRequest(uri, HttpMethod.POST);
ClientHttpResponse res = chr.execute();
InputStream is = res.getBody(); //获得返回数据,注意这里是个流
InputStreamReader isr = new InputStreamReader(is);
BufferedReader br = new BufferedReader(isr);
String str = "";
while ((str = br.readLine()) != null) {
if (!str.equals(BjBiyingConstant.NOTIFY_TICKET_SUCCESS_CODE)) {
if (resendCount < 3) {
resendCount++;
run();
}
//run();//chong fa
}
System.out.println(str);//获得页面内容或返回内容
}
} catch (URISyntaxException e1) {
// TODO Auto-generated catch block
e1.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
通过获取单例调用静态对象执行线程方法:
ThreadPool.getInstance().getExecutor().schedule(new BjSendNotifyTicket(paramsS.toString()), 5L, TimeUnit
.MILLISECONDS);