异步线程无法多次创建的问题

最近在做安卓程序过程中,写了一个按钮走秒的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();
	}

	@Override
	protected 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;
	}

	@Override
	protected 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
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值