ThreadPoolExecutor:获取正在执行的特定Runnable

时间:2017-02-06 15:10:29

标签: java android multithreading runnable threadpoolexecutor

我正在使用ThreadPoolExecutor在后​​台执行多个长时间运行的任务,池ThreadPoolExecutor的大小为4,因此当添加4个以上的任务时,它们会被推送到队列,当4个中的一个任务完成后,一个任务从队列中执行以便执行。

我想知道有没有办法访问当前正在执行但不在队列中的Runnable对象,即前4个任务。

目标:我希望在mThreadPoolExecutor.getQueue()的帮助下,在任何给定点获取任务的当前状态。我正在访问排队并准备执行的任务,请建议我访问这些任务的方法当前正在执行,以便我可以在需要时附加和删除侦听器/处理程序。

我的Runnable类:

public class VideoFileUploadRunner implements Runnable {

    private final VideoFileSync mVideoFileSync;
    private final DataService dataService;

    private Handler handler;

    public VideoFileUploadRunner(VideoFileSync videoFileSync, DataService dataService) {
        this.mVideoFileSync = videoFileSync;
        this.dataService = dataService;

    }

    public int getPK()
    {
        return  mVideoFileSync.get_idPrimaryKey();
    }

    public void setHandler(Handler handler) {
        this.handler = handler;
    }

    @Override
    public void run() {
        try {

            if (mVideoFileSync.get_idPrimaryKey() < 0) {
                addEntryToDataBase();
            }
            updateStatus(VideoUploadStatus.IN_PROGRESS);
            FileUploader uploader = new FileUploader();
            updateStatus(uploader.uploadFile(mVideoFileSync.getVideoFile()));



        } catch (Exception e) {
            updateStatus(VideoUploadStatus.FAILED);
            e.printStackTrace();
        }
    }

    private void addEntryToDataBase() {
        int pk = dataService.saveVideoRecordForSync(mVideoFileSync);
        mVideoFileSync.set_idPrimaryKey(pk);
    }

    private void updateStatus(VideoUploadStatus status) {
        if (handler != null) {
            Message msg = new Message();
            Bundle b = new Bundle();
            b.putString(AppConstants.Sync_Status, status.toString());
            msg.setData(b);
            handler.sendMessage(msg);
        }
        dataService.updateUploadStatus(mVideoFileSync.get_idPrimaryKey(), status.toString());


    }
} 

在任务进度列表视图持有者中:

public void setData(VideoFileSync fileSync) {
        tvIso.setText(fileSync.getVideoFile().getISO_LOOP_EQUP());
        tvUnit.setText(fileSync.getVideoFile().getUnit());
        tvName.setText(fileSync.getVideoFile().getLocalPath());
        tvStatus.setText(fileSync.getCurentStatus().toString());
        addHandleForUpdate(fileSync);
    }

    private void addHandleForUpdate(VideoFileSync fileSync) {

        Handler.Callback callBack = new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if(msg.getData()!=null)
                {
                    tvStatus.setText(msg.getData().getString(AppConstants.Sync_Status));

                }
                return false;
            }
        };
        mHadler = new Handler(Looper.getMainLooper(),callBack);

        VideoFileUploadRunner runner = VideoUploadManager.getInstance().getRunnerForSyncFile(fileSync);
        if(runner!=null)
        runner.setHandler(mHadler);
    }
在VideoUploadManager中的

我有以下方法返回Runnable对象,在这里我需要帮助,以便我可以返回当前正在执行的任务。

public synchronized VideoFileUploadRunner getRunnerForSyncFile(VideoFileSync fileSync) {
        Iterator<Runnable> itr = mThreadPoolExecutor.getQueue().iterator();
        while (itr.hasNext()) {
            VideoFileUploadRunner runner = (VideoFileUploadRunner) itr.next();
            if (runner.getPK() == fileSync.get_idPrimaryKey()) {
                return runner;
            }
        }
        return null;

    } 

3 个答案:

答案 0 :(得分:0)

最好的方法是公开一个同步变量,其中包含当前正在执行的任务的信息。

public MyTask implements Runnable {
    private String id;
    private Map<String, MyTask> mapTasks;

    public MyTask(String id, Map<String, MyTask> mapTasks) {
        this.id = id;
        this.mapTasks = mapTasks;
    }

    public void run() {
         synchronized(mapTasks) {
             mapTasks.put(id, this);
         }

         ...

         synchronized(mapTasks) {
             mapTasks.remove(id);
         }
    }
}


// Create a map of tasks
Map<String, MyTask> mapTasks = new HashMap<String, MyTask>();

// How to create tasks
MyTask myTask1 = new MyTask("task1", mapTasks);
MyTask myTask2 = new MyTask("task2", mapTasks);

executorService.execute(myTask1);
executorService.execute(myTask2);

....

并打印当前正在执行的任务列表:

public void printCurrentExecutingTasks(Map<String, MyTask> tasks) {
    for (String id: tasks.keySet()) {
        System.out.println("Executing task with id: " + id);
    }
}

答案 1 :(得分:0)

我的回答专注于问题:“如何知道正在执行哪些runnable”。

此方法保留活动Runnables的并发Set:

private final Set<VideoFileUploadRunner> active = Collections.newSetFromMap(new ConcurrentHashMap<>());

提交给ThreadPoolExecutor的Runnables应该使用Runnable进行修饰,以更新此集:

class DecoratedRunnable implements Runnable {

    final VideoFileUploadRunner runnable;

    public DecoratedRunnable(VideoFileUploadRunner runnable) {
        this.runnable = runnable;
    }

    @Override
    public void run() {
        active.add(runnable); // add to set
        try {
            runnable.run();
        } finally {
            active.remove(runnable); // finally remove from set (even when something goes wrong)
        }
    }
}

因此我们可以在提交之前装饰VideoFileUploadRunner个实例:

executorService.submit(new DecoratedRunnable(videoFileUploadRunner));

方法getRunnerForSyncFile将简单地实现如下:

public VideoFileUploadRunner getRunnerForSyncFile(VideoFileSync fileSync) {
    return active.stream()
            .filter(videoFileUploadRunner -> videoFileUploadRunner.getPK() == fileSync.get_idPrimaryKey())
            .findAny()
            .orElse(null);
}

备注:正如@Charlie所述,这不是将侦听器附加到Runnable的最佳方式。您可以请求从VideoFileUploadRunner的{​​{1}}方法内部设置消息处理程序,或者使用MessageHandler集初始化此类实例,或者使用此装饰方法将其保留在{{1}之外} class。

答案 2 :(得分:0)

这个答案与我上面的评论有关。

不是试图通过执行程序找到runnable并将侦听器附加到它,而是在创建它时将侦听器绑定到runnable,并从runnable的执行代码将事件发布到侦听器。

只有当前活动的runnables才会发布更新。

以下是一个例子。

为您的侦听器创建一个实现的接口。您的侦听器可以是线程池执行器,私有内部类等。

/** 
 * Callback interface to notify when a video upload's state changes 
 */
interface IVideoUploadListener {

    /**
     * Called when a video upload's state changes

     * @param pUploadId The ID of the video upload
     * @param pStatus The new status of the upload
     */
    void onStatusChanged(int pUploadId, VideoUploadStatus pStatus);
}

为您的状态类型创建枚举(例如)

/**
 * Enum to hold different video upload states
 */
enum VideoUploadStatus {
    IN_PROGRESS,
    ADDED_TO_DB,
    FILE_UPLOADED,
    FINISHED,
    FAILED
}

在每个Runnable中保留侦听器的引用。

public class VideoFileUploadRunner implements Runnable {

    private final IVideoUploadListener mUploadListener;
    private final VideoFileSync mVideoFileSync;
    private final DataService   mDataService;
    private Handler mHandler;

    // etc...
}

通过构造函数

传递接口的实例
public VideoFileUploadRunner(IVideoUploadListener pUploadListener, VideoFileSync pVideoFileSync, DataService pDataService) {
    mUploadListener = pUploadListener;
    mVideoFileSync  = pVideoFileSync;
    mDataService    = pDataService;
}

在run方法中,根据需要发布对侦听器的更新。

@Override
public void run() {
    mUploadListener.onStatusChanged(getPrimaryKey(), VideoUploadStatus.IN_PROGRESS);
    try {
        if (mVideoFileSync.get_idPrimaryKey() < 0) {
            addEntryToDataBase();
            mUploadListener.onStatusChanged(getPrimaryKey(), VideoUploadStatus.ADDED_TO_DB);
        }
        FileUploader uploader = new FileUploader();
        uploader.uploadFile(mVideoFileSync.getVideoFile());
        mUploadListener.onStatusChanged(getPrimaryKey(), VideoUploadStatus.FILE_UPLOADED);

        // Other logic here...

        mUploadListener.onStatusChanged(getPrimaryKey(), VideoUploadStatus.FINISHED);
    }

    catch (Exception e) {
        mUploadListener.onStatusChanged(getPrimaryKey(), VideoUploadStatus.FAILED);
        e.printStackTrace();
    }
}

onStatusChanged()方法的侦听器实现应该同步。这有助于避免竞争条件造成的错误结果。

private IVideoUploadListener mUploadListener = new IVideoUploadListener() {
    @Override
    public synchronized void onStatusChanged(int pUploadId, VideoUploadStatus pStatus) {
        Log.i("ListenerTag", "Video file with ID " + pUploadId + " has the status " + pStatus.toString());
    }
};