一线程池的使用
1.线程池的原理
public class ThreadPool {
int maxCount = 3;
AtomicInteger count =new AtomicInteger(0);// 当前开的线程数 count=0,atomicInteger可以保持线程同步
LinkedList<Runnable> runnables = new LinkedList<Runnable>();
public void execute(Runnable runnable) {
runnables.add(runnable);
if(count.incrementAndGet()<=3){
createThread();
}
}
private void createThread() {
new Thread() {
@Override
public void run() {
super.run();
while (true) {
// 取出来一个异步任务
if (runnables.size() > 0) {
Runnable remove = runnables.remove(0);
if (remove != null) {
remove.run();
}
}else{
// 等待状态 wake();
}
}
}
}.start();
}
}
2.线程池的使用
public class ThreadManager {
private ThreadManager() {
}
private static ThreadManager manager = new ThreadManager();
private ThreadPoolProxy longPool ;
private ThreadPoolProxy shortPool ;
public static ThreadManager getInstance() {
return manager;
}
/** 操作网络文件的线程*/
// cpu的核数*2+1
public synchronized ThreadPoolProxy createLongPool() {
if (longPool == null) {
longPool = new ThreadPoolProxy(5, 5, 5000L);
}
return longPool;
}
/** 操作本地文件的线程*/
public synchronized ThreadPoolProxy createshortPool() {
if (shortPool == null) {
shortPool = new ThreadPoolProxy(3, 3, 5000L);
}
return shortPool;
}
public class ThreadPoolProxy {
private ThreadPoolExecutor pool;
private int corePoolSize;
private int maximumPoolSize;
private long time;
public ThreadPoolProxy(int corePoolSize, int maximumPoolSize, long time) {
this.corePoolSize = corePoolSize;
this.maximumPoolSize = maximumPoolSize;
this.time = time;
}
public void execute(Runnable runnable) {
/*
* 1.线程池里面管理的线程数2.如果排队满了额外再开的线程数3.如果线程池没有要执行的任务 存活多久4.时间的单位5.如果
* 线程池里管理的线程都已经用了,剩下的任务 临时存到LinkedBlockingQueue对象中 排队10个排队
*/
if (pool == null) {
pool = new ThreadPoolExecutor(corePoolSize, maximumPoolSize,
time, TimeUnit.MILLISECONDS,
new LinkedBlockingQueue<Runnable>(10));
}
pool.execute(runnable);
}
public void cancel(Runnable runnable) {
// 不为null ,没有停止,,没有崩溃
if (pool != null && !pool.isShutdown() && !pool.isTerminated()) {
pool.remove(runnable);
}
}
}
}
二。读取网络数据
1.BaseProtocol
public abstract class BaseProtocol<T> {
private FileWriter writer;
private BufferedWriter bufferedWriter;
private BufferedReader bufferedReader;
private JSONArray jsonArray;
private T parseJson;
public T load(int index) {
String json = loadLocal(index);// 1.加载本地数据
System.out.println("加载了本地数据");
if (json == null) {// 2.没有本地数据,则加载服务器数据
json = loadServer(index);
// System.out.println(json);
if (json != null) {
saveLocal(index, json);// 3.保存数据到本地
}
}
if (json != null) {// 4.如果加载到了本地数据,解析
parseJson = parseJson(json);
return parseJson;
} else {
return null;
}
}
/** 1.加载本地数据 */
private String loadLocal(int index) {
File dir = FileUtils.getFilePath("cache");
File file = new File(dir, getKey() + index);// 缓存在sdcard/google1/cache文件夹中
if (file != null) {
try {
bufferedReader = new BufferedReader(new FileReader(file));
long time = Long.parseLong(bufferedReader.readLine());
if (System.currentTimeMillis() - time > 0) {
return null;
} else {
StringWriter stringWriter = new StringWriter();
String str;
while ((str = bufferedReader.readLine()) != null) {
stringWriter.write(str);
}
return stringWriter.toString();
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
IOUtils.closeQuietly(bufferedReader);
}
}
return null;
}
/** 2.加载服务器数据 */
private String loadServer(int index) {
// 这里为什么不用在子线程中运行,因为调用的时候就是在子线程中调用的,用httputils的话里面涉及线程中的线程问题
StringBuffer buffer = null;
HttpURLConnection connection = null;
try {
URL url = new URL("http://127.0.0.1:8090/" + getKey() + "?index="
+ index + getParams());
connection = (HttpURLConnection) url.openConnection();
connection.setRequestMethod("GET");
connection.setReadTimeout(8000);
connection.setConnectTimeout(8000);
connection.connect();
if (connection.getResponseCode() == 200) {
InputStream stream = connection.getInputStream();
BufferedReader reader = new BufferedReader(
new InputStreamReader(stream));
buffer = new StringBuffer();
String line = "";
while ((line = reader.readLine()) != null) {
buffer.append(line);
}
}
} catch (Exception e) {
e.printStackTrace();
return null;
} finally {
if (connection != null) {
connection.disconnect();
}
}
return buffer.toString();
}
private void saveLocal(int index, String json) {
try {
File dir = FileUtils.getFilePath("cache");
File file = new File(dir, getKey() + index);// 缓存在sdcard/google1/cache文件夹中
writer = new FileWriter(file);
bufferedWriter = new BufferedWriter(writer);
bufferedWriter.write(System.currentTimeMillis() + "");
bufferedWriter.newLine();
bufferedWriter.write(json);
bufferedWriter.close();
} catch (Exception e) {
e.printStackTrace();
} finally {
IOUtils.closeQuietly(writer);
IOUtils.closeQuietly(bufferedWriter);
}
}
public abstract T parseJson(String json);
public abstract String getKey();
public abstract String getParams();
}
2.获取缓存在本地的路径
public class FileUtils {
public static final String URL = "http://127.0.0.1:8090/";
private static final String Root = "google1";
public static final String ICON = "icon";
String path = "";
private static StringBuilder stringBuilder;
/**
* 获取图片的缓存的路径
* @return
*/
public static File getIconDir(){
return getFilePath(ICON);
}
/**
* 获取缓存路径
* @return
*/
public static File getCacheDir() {
return getFilePath("");
}
//获取缓存的路径
public static File getFilePath(String str) {
if (Environment.getExternalStorageState().equals(
Environment.MEDIA_MOUNTED)) {
stringBuilder = new StringBuilder();
stringBuilder.append(Environment.getExternalStorageDirectory()
.getAbsolutePath());
stringBuilder.append(File.separator);
stringBuilder.append(Root);
stringBuilder.append(File.separator);
stringBuilder.append(str);
}else{
File filesDir = BaseApplication.getApplication().getFilesDir();
stringBuilder.append(filesDir.getAbsolutePath());
stringBuilder.append(File.separator);
stringBuilder.append(str);
}
File file = new File(stringBuilder.toString());
// 不存在或者不是一个文件夹
if (!file.exists() || !file.isDirectory()) {
file.mkdirs();
}
return file;
}
}
3.HomeProtocol解析数据
public class HomeProtocol extends BaseProtocol<List<Appinfo>>{
private JSONArray jsonArray;
public List<Appinfo> parseJson(String json) {
JSONObject jsonObject;
List<Appinfo> appinfos = new ArrayList<Appinfo>();
try {
jsonObject = new JSONObject(json);
jsonArray = jsonObject.getJSONArray("list");
for (int i = 0; i < jsonArray.length(); i++) {
JSONObject jsonObject2 = jsonArray.getJSONObject(i);
long id = jsonObject2.getLong("id");
String name = jsonObject2.getString("name");
String packageName = jsonObject2.getString("packageName");
String iconUrl = jsonObject2.getString("iconUrl");
float stars = Float.parseFloat(jsonObject2.getString("stars"));
long size = jsonObject2.getLong("size");
String downloadUrl = jsonObject2.getString("downloadUrl");
String des = jsonObject2.getString("des");
Appinfo appinfo = new Appinfo(id, name, packageName, iconUrl,
stars, size, downloadUrl, des);
appinfos.add(appinfo);
}
return appinfos;
} catch (JSONException e) {
e.printStackTrace();
return null;
}
}
public String getKey() {
return "home";
}
/** 重写这个后缀,有的有,有的没有,需要的重写 */
public String getParams() {
return "";
}
}
4.设置HomeFragment页面
public class HomeFragment extends BaseFragment {
private List<Appinfo> data;
private ListView listView;
private Myadapter myadapter;
private BitmapUtils bitmapUtils;
// 开始的时候就加载HomeFragment的页面
@Override
public void onActivityCreated(@Nullable Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
show();
}
/** 创建了成功的界面 */
protected View createSuccessView() {
listView = new ListView(BaseApplication.getApplication());
myadapter = new Myadapter();
// listView.setAdapter(myadapter);
return listView;
}
class Myadapter extends BaseAdapter {
@Override
public int getCount() {
return data.size();
}
@Override
public Object getItem(int position) {
return data.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
ViewHolder holder;
if (convertView == null) {
holder = new ViewHolder();
view = View.inflate(BaseApplication.getApplication(),
R.layout.item_app, null);
holder.item_icon = (ImageView) view
.findViewById(R.id.item_icon);
holder.item_title = (TextView) view
.findViewById(R.id.item_title);
holder.item_size = (TextView) view.findViewById(R.id.item_size);
holder.item_bottom = (TextView) view
.findViewById(R.id.item_bottom);
holder.item_rating = (RatingBar) view
.findViewById(R.id.item_rating);
view.setTag(holder);
} else {
view = convertView;
holder = (ViewHolder) view.getTag();
}
Appinfo appinfo = data.get(position);
holder.item_title.setText(appinfo.getName());
String formatFileSize = Formatter.formatFileSize(
BaseApplication.getApplication(), appinfo.getSize());
holder.item_size.setText(formatFileSize);
holder.item_bottom.setText(appinfo.getDes());
holder.item_rating.setRating(appinfo.getStarts());
//http://127.0.0.1:8090/image?name=app/com.youyuan.yyhl/icon.jpg
// 加载图片
String iconUrl = appinfo.getIconUrl();
System.out.println(iconUrl+"-------------");
bitmapUtils = BitmapHelper.getBitmapUtils();//使用单例模式的BitmapUtils,并且可以缓存到sdcard中
bitmapUtils.display(holder.item_icon,"http://127.0.0.1:8090" + "/image?name=" + iconUrl);
bitmapUtils.configDefaultLoadingImage(R.drawable.ic_launcher);
return view;
}
}
// 获取数据从服务器
protected int LoadDataFromServer() {
HomeProtocol homeProtocol = new HomeProtocol();
data = homeProtocol.load(0);
for (Appinfo appinfo : data) {
// System.out.println(appinfo.toString());
}
getActivity().runOnUiThread(new Runnable() {
@Override
public void run() {
listView.setAdapter(myadapter);
}
});
return checkData(data);
}
static class ViewHolder {
ImageView item_icon;
TextView item_title;
TextView item_size;
TextView item_bottom;
RatingBar item_rating;
}
}
5.使用BitmapUtils的方法可以将图片缓存到本地中
public class BitmapHelper {
private BitmapHelper() {
}
private static BitmapUtils bitmapUtils;
/**
* BitmapUtils不是单例的 根据需要重载多个获取实例的方法
*
* @param appContext
* application context
* @return
*/
public static BitmapUtils getBitmapUtils() {
if (bitmapUtils == null) {
// 第二个参数 缓存图片的路径 // 加载图片 最多消耗多少比例的内存 0.05-0.8f
bitmapUtils = new BitmapUtils(UiUtils.getContext(), FileUtils
.getIconDir().getAbsolutePath(), 0.3f);
}
return bitmapUtils;
}
}
6.设置ListView的细节处理
## BaseListView
public class BaseListView extends ListView {
public BaseListView(Context context) {
super(context);
init();
}
public BaseListView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
public BaseListView(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
private void init() {
// setSelector 点击显示的颜色
// setCacheColorHint 拖拽的颜色
// setDivider 每个条目的间隔 的分割线
this.setSelector(R.drawable.nothing); // 什么都没有
this.setCacheColorHint(R.drawable.nothing);
this.setDivider(UiUtils.getDrawalbe(R.drawable.nothing));
}
}