一个应用,如果并发操作过多,就会导致卡顿,用户体验很不好。
我们可以通过线程池的方式,从某种角度来控制并发数,但是这就要求我们写代码的时候严格规范,能发现的耗时操作都放到线程池。
下面是我自己写的一个工具类,也可以直接将里面代码扔到application。
不多哔哔,上代码:
public class AppThreadPool {
/**
* 单例,可以将该类放到Application中,实现整个APP控制线程的目的
*/
private static AppThreadPool pool;
/**
* 线程池
*/
ExecutorService tPool;
/**
* 连接超时时间
*/
private static final int connectionTime = 5000;
/**
* read超时时间
*/
private static final int readTime = 10000;
/**
* 单例获取,否则线程池失去目的,不如直接new Thread来得爽
* @return
*/
public static AppThreadPool getPool() {
if (pool == null) {
pool = new AppThreadPool();
}
return pool;
}
public AppThreadPool() {
// TODO Auto-generated constructor stub
int count = getCPUcount();
tPool = Executors.newFixedThreadPool(count);
}
/**
* 获取设备CPU核心数,用来设置线程池大小
* 小于8则固定返回5,大于等于8则返回核心数的四分之三
* @return
*/
private int getCPUcount() {
int xxx = Runtime.getRuntime().availableProcessors();
if (xxx < 8) {
return 5;
} else {
return xxx / 3 * 4;
}
}
/**
* 请求数据
* @param httpurl 请求地址
* @param headers 请求头,某些特殊场景需要
* @return
*/
public String get(String httpurl, Map
headers) {
if (tPool == null) {
int count = getCPUcount();
tPool = Executors.newFixedThreadPool(count);
}
Future
future = tPool.submit(new MyTask(httpurl, headers));
String result = "";
try {
result = future.get();
} catch (Exception e) {
// TODO: handle exception
}
return result;
}
class MyTask implements Callable
{
private String httpurl;
private Map
headers;
public MyTask(String httpurl, Map
headers) { // TODO Auto-generated constructor stub this.httpurl = httpurl; this.headers = headers; } @Override public String call() throws Exception { // TODO Auto-generated method stub String result = ""; URL url = null; HttpURLConnection connection = null; InputStreamReader in = null; try { url = new URL(httpurl); connection = (HttpURLConnection) url.openConnection(); if (null != headers && headers.size() > 0) { Iterator
it = headers.keySet().iterator(); while (it.hasNext()) { String k = it.next(); connection.setRequestProperty(k, headers.get(k)); } } connection.setConnectTimeout(connectionTime); connection.setReadTimeout(readTime); connection.connect(); in = new InputStreamReader(connection.getInputStream()); BufferedReader bufferedReader = new BufferedReader(in); StringBuffer strBuffer = new StringBuffer(); String line = null; while ((line = bufferedReader.readLine()) != null) { strBuffer.append(line); } result = strBuffer.toString(); } catch (Exception e) { e.printStackTrace(); } finally { if (connection != null) { connection.disconnect(); } if (in != null) { try { in.close(); } catch (IOException e) { e.printStackTrace(); } } } return result; } } }
调用:String xxx = AppThreadPool.getPool().get("http://int.dpool.sina.com.cn/iplookup/iplookup.php?format=json&ip=", null);
System.out.println("activity---" + xxx);
类里面只做了get请求访问,相信各位能看懂都能写其他。