我在android中使用多线程一切顺利,但我无法维护所有线程
我和你们分享了一些代码,请帮帮我
ThreadPool.java
public class ThreadPool {
private long index = 0;
private static Hashtable<Long, ThreadPool> list = new Hashtable<Long, ThreadPool>(
5);
private ArrayList<Future<?>> futureList = null;
private String TAG;
private ThreadPool(int poolSize) {
executorService = Executors.newFixedThreadPool(poolSize);
futureList = new ArrayList<Future<?>>(30);
index = System.currentTimeMillis();
list.put(index, this);
}
public static ThreadPool getNewIntance(int poolSize) {
return new ThreadPool(poolSize);
}
/**
* executes a Runnable instance.
*
* @param task
*/
public Future<?> execute(Runnable task) {
Future<?> future = null;
if (executorService != null) {
future = executorService.submit(task);
futureList.add(future);
}
return future;
}
}
HttpGetRequest.java
public class HttpGetRequest implements Runnable {
private final static int TIMEOUT = 10000;
// private static final String TAG = "Http Request";
private String urlstring;
private int action;
private String data;
private HttpCallback cb;
private HashMap<String, String> params = null;
public HttpGetRequest(String url, HashMap<String, String> params,
int action, HttpCallback cb, String data) {
this.urlstring = url;
this.cb = cb;
this.action = action;
this.params = params;
this.data = data;
}
public void run() {
String rawResponse = null;
InputStream inputStream = null;
HttpURLConnection conn = null;
try {
URL url = new URL(urlstring);
conn = (HttpURLConnection) url.openConnection();
conn.setReadTimeout(TIMEOUT);
conn.setConnectTimeout(TIMEOUT);
conn.setRequestMethod("GET");
conn.setDoInput(true);
conn.connect();
inputStream = conn.getInputStream();
BufferedReader bReader = new BufferedReader(new InputStreamReader(
inputStream));
StringBuffer sb = new StringBuffer();
String line = "";
while ((line = bReader.readLine()) != null) {
sb.append(line);
}
rawResponse = sb.toString();
} catch (IOException e) {
e.printStackTrace();
} finally {
conn.disconnect();
try {
if (inputStream != null) {
inputStream.close();
}
} catch (IOException e) {
e.printStackTrace();
}
}
cb.onResponse(rawResponse, action, data);
}
}
HttpCallback.java
//interface
public interface HttpCallback {
/**
* Callback method for http response. called when an http response is
* received.
*
* @param response
* @param action
* @param data
* that you want to pass and get it while callback in response
*/
public void onResponse(String response, int action, String data);
}
mainActivity.java
public class UserProfileActivity extends AppCompatActivity implements
HttpCallback,
{
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
HttpGetRequest likesRequest = new HttpGetRequest(
url, param,ACTION_TYPE_LIKE, httpCallback,
strData);
InstaApplication.threadPool.execute(likesRequest);
}
@Override
public void onResponse(String response, int action, String data) {
switch (action) {
case 1:
//handle response here
break;
}
}