异步线程无法多次创建的问题
来源:互联网 发布:天涯八卦是什么软件 编辑:程序博客网 时间:2024/04/28 20:06
最近在做安卓程序过程中,写了一个按钮走秒的messageBox控件,走秒的实现是用异步线程AsyncTask实现的,具体如下
public class TimerDisplay extends AsyncTask<Void, Integer, Void> {private int count = 10;private Button handlerButton;private AlertDialog currentAlertDialog;private String handlerText = null;public TimerDisplay(Button handlerButton, AlertDialog currentAlertDialog) {this.handlerButton = handlerButton;this.currentAlertDialog = currentAlertDialog;this.handlerText = handlerButton.getText().toString();}@Overrideprotected Void doInBackground(Void... params) {try {while (count >= 0) {if (currentAlertDialog.isShowing()) {publishProgress(count);count--;Thread.sleep(1000);} else {count = -999;}}} catch (InterruptedException e) {e.printStackTrace();}return null;}@Overrideprotected void onProgressUpdate(Integer... values) {if (values[0] > 0) {handlerButton.setText(handlerText + " (" + String.valueOf(values[0]) + ")");super.onProgressUpdate(values);} else if (values[0] == 0) {handlerButton.performClick();currentAlertDialog.dismiss();}}}
在外层调用该类的方式如下:
TimerDisplay td = new TimerDisplay(positiveButton, alertDialog);td.execute();最后发现了这样一个bug
该messageBox在应用中多次创建时,且每次都是在走秒未走完时,关闭掉dialoge,循环操作次数达到7次以上时,messageBox不会出现走秒的情况了
在查找问题的过程中,发现每次之所以出现不走秒的情况,是因为异步线程没有走doInBackground()方法,在代码中打log发现虽然没有走doInBackground()方法,但是走了
onPreExecute() 方法,且线程处于running状态,
最后查找问题发现异步线程在设计之初,就有一个个数限制,当超过这个个数之后,线程就不会被执行,
解决办法是
http://stackoverflow.com/questions/16832376/asynctask-doinbackground-not-called
TimerDisplay td = new TimerDisplay(positiveButton, alertDialog); FULL_TASK_EXECUTOR = (ExecutorService) Executors.newCachedThreadPool(); td.executeOnExecutor(FULL_TASK_EXECUTOR);
创建线程池,把异步线程放在线程池中,当线程没有使用时,会被移出线程池,这个每次创建异步线程都能成功
0 0
- 异步线程无法多次创建的问题
- 线程多次创建的问题
- 多次出现无法连接的问题!
- Qt 多次重启线程的问题
- 多次调用异步任务(AsyncTask)时出现的问题
- ajaxFileUpload异步上传资源,onchange多次调用问题的解决方案
- 同一线程多次创建 的 线程资源释放问题在每个线程的一开始,用pthred_detach(pthread_self())来使自己detach掉
- HandlerThread 创建一个异步的后台线程
- NameNode多次Format后DataNode无法启动的问题
- 多次弹出ShowModalDialog无法取到returnValue的问题
- Python守护线程被多次运行的问题【摘记】
- GCD 创建异步线程
- Toast 多次创建显示问题
- Toast 多次创建显示问题
- Android多进程所产生的问题-Applicaion多次创建
- iOS线程的同步异步问题
- 关于线程创建的问题
- MFC创建线程的问题
- Python正则-多行匹配
- HBase简介(很好的梳理资料)
- Java二进制Class文件格式解析
- 菜鸟学习oracle
- VMware虚拟机XP系统安装图文教程
- 异步线程无法多次创建的问题
- 指向指针的学生
- Pat(Advanced Level)Practice--1052(Linked List Sorting)
- gcc configure: error: Building GCC requires GMP 4.2+, MPFR 2.3.1+ and MPC 0.8.0
- 第四周作业——图的表示
- JPA 2.0 Concurrency and locking
- 根据年月日计算星期几的函数
- 朴素贝叶斯分类器
- MFC关于消息响应的宏代码