您的位置:首页 > 移动开发 > Android开发

Android实际开发中用到的线程池

2016-03-15 17:24 274 查看
实际开发中所用到的线程池管理类

/**
* Created by jiangxiangfei on 2016/3/9.
*/
public class ThreadPoolManager {

private int corePoolSize;
private int maximumPoolSize;
private int keepAliveTime = 1;
private TimeUnit unit = TimeUnit.HOURS;
private static ThreadPoolManager mInstance = new ThreadPoolManager();
private ThreadPoolExecutor executor;

private ThreadPoolManager(){
corePoolSize = Runtime.getRuntime().availableProcessors()*2 + 1;
maximumPoolSize = corePoolSize;
executor = new ThreadPoolExecutor(
corePoolSize,
maximumPoolSize,
keepAliveTime,
unit,
new LinkedBlockingQueue<Runnable>(),
Executors.defaultThreadFactory(),
new ThreadPoolExecutor.AbortPolicy());

}

public static ThreadPoolManager getInstance(){
return mInstance;
}
/**
* 添加任务
* @param runnable
*/
public void execute(Runnable runnable){
if(runnable==null) return;

executor.execute(runnable);
}

/**
* 移除任务
* @param runnable
*/
public void remove(Runnable runnable){
if(runnable==null) return;

executor.remove(runnable);
}
}


实际使用代码

是为点赞准备的:没有硬性的要求每一次的点赞都要成功;有怕主线程阻塞的问题。还要操作本地数据库:所以使用线程池

具体使用代码:listview条目中的点击事件

holder.fragment_content_lv_item_islike_group.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
Log.e("jxf","进入点击事件了");
contents.get(position).isThumbs=1;
contents.get(position).thumbsCount+=1;

Intent intent0=new Intent();
intent0.setAction("player_callNewBack_refresh");
Log.e("jxf", "给newcontentfragment广播响应");
intent0.putExtra("refreshteacherId", contents.get(position).teacherId);
context.sendBroadcast(intent0);

ContentAdapter.this.notifyDataSetChanged();
Log.e("jxf","界面刷新了");

ThreadPoolManager.getInstance().execute(new Runnable() {
@Override
public void run() {
Log.e("jxf","修改数据库");
ContentValues values=new ContentValues();
values.put("is_thumbs",1);
values.put("thumbs_count", contents.get(position).thumbsCount);
App.getSqlManager().updateOne("contents", values, "teacher_id=? and is_thumbs=?", new String[]{"" + contents.get(position).teacherId,""+0});

String path = Url.ADD_THUMBS+"?userId="+(int) SharedPreUtils.get(context, "user_id", 0)+"&teacherId="+(long)contents.get(position).teacherId;
Log.e("jxf","打印path"+path);
HttpClient client = new DefaultHttpClient();
HttpGet get = new HttpGet(path);
//加头
String userLoginName = (String)SharedPreUtils.get(context,"user_login_name","");
String password = (String)SharedPreUtils.get(context,"user_password","");
Log.e("jxf", "headGet提交请求携带头部信息useragent" + App.httpUserAgent);
get.addHeader("User-Agent", App.httpUserAgent);
Log.e("jxf", "headGet提交请求携带头部信息userLoginName" + userLoginName);
get.addHeader("userLoginName", userLoginName);
Log.e("jxf", "请求携带头部信息passwd"+password);
get.addHeader("passwd", password);
try {
client.execute(get);
} catch (IOException e) {
e.printStackTrace();
Log.e("jxf","点赞请求发生异常"+e.toString());
}
}
});

}
});
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android 线程池 管理