异步任务Android中的java.util.concurrent.RejectedExecutionException

时间:2012-08-22 14:08:03

标签: android multithreading listview android-asynctask

public View getView(final int position, View convertView, ViewGroup parent) {
    SectionHolder sectionHolder = null;
    ViewHolder holder = null;
    convertView = listAdapter.getView(getIndexForPosition(position),
                convertView, parent);
    convertView.setTag(contactsIds[getIndexForPosition(position)]);
    holder = new ViewHolder();
    holder.txtTitle = (TextView) convertView
                .findViewById(R.id.list_item_title);
    holder.id = contactsIds[getIndexForPosition(position)];
    new ThumbnailTask(holder,contactsIds[getIndexForPosition(position)]).execute();
    return convertView;
}

private class ThumbnailTask extends AsyncTask<Void, Void, Integer> {
    private String mId;
    private ViewHolder mHolder;
    public ThumbnailTask(ViewHolder holder, String id) {
        mId = id;
        mHolder = holder;
    }

    @Override
    protected Integer doInBackground(Void... params) {
        // TODO Auto-generated method stub
        int drawableId = getContactStatus(mHolder.id);
        // Log.i("DRAWABLE",drawableId+"");
        return drawableId;
    }

    protected void onPostExecute(Integer drawableId) {
        if (mHolder.id.equals(mId)) {
            if (drawableId != 0) {
                if (UpdateStatusService.user == 1) {
                    mHolder.txtTitle.setCompoundDrawablesWithIntrinsicBounds(0, 0,drawableId, 0);
                } else {
                    mHolder.txtTitle.setCompoundDrawablesWithIntrinsicBounds(0, 0,R.drawable.ic_action_quetion, 0);
                }
            } else {
                    mHolder.txtTitle.setCompoundDrawablesWithIntrinsicBounds(0,0, android.R.color.transparent, 0);
            }
        }
    }
}
static class ViewHolder {
    public TextView txtTitle;
    public String id;
}

这是我对listview的getView的适配器代码。

ListView包含来自android的联系人列表。

但我得到 java.util.concurrent.RejectedExecutionException 异步任务基本上从服务器获取图像,如果任何数字与将包含一个图像的服务器数据匹配,否则不会。

那么我该怎么做才能避免这种异常呢?

1 个答案:

答案 0 :(得分:10)

AsyncTask个线程放在工作队列中。该工作队列限制了可以实例化的线程数。当你超过最大值时,它会给你一个RejectedExecutionException

解决方案是重构代码以不在getView()中实例化线程,或者使用检查来控制当前行的线程是否已经启动。 getView()被非常频繁地调用,因此如果你没有检查一个线程当前是否在一行上运行,你最终会超过允许的线程数。

下载链接:https://www.dropbox.com/s/pvr9zyl811tfeem/ListViewImageCache.zip