简体   繁体   English

如何在此代码中跟踪多个异步任务

[英]How do I keep track of multiple Asynchronous Tasks in this code

I am creating an option for the users to pause, or schedule a task. 我正在为用户创建一个暂停或安排任务的选项。 Based on the program I am limiting it to 2 pauses, that can happen in parallel or in series. 基于该程序,我将其限制为2次暂停,这可以并行或串行发生。 I thought the easiest way to do it was to setup two different Runnables. 我认为最简单的方法是设置两个不同的Runnables。 However if Task 1 < Task 2, and Task 2 is instigated before the end of Task 1, Task 1 shuts Task 2 down. 但是,如果在任务1结束之前发起任务1 <任务2和任务2,则任务1关闭任务2。

For the sake of argument, Task 1 is a 5 second delay, Task 2 is a 10 second delay. 为了论证,任务1是5秒延迟,任务2是10秒延迟。 Task 2 gets trigger 1 second into Task 1. When Task 1 finishes, it appears that Task2 has finished. 任务2在任务1中获得1秒触发。当任务1完成时,似乎Task2已完成。

threadNumber is an int I set when the task is called to keep track of the results. threadNumber是我在调用任务时设置的int,用于跟踪结果。

They are not acting independent and are being commingled 他们不是独立行动,而是混合在一起

I broke the Runnables into two distinct elements, triggered by a switch/case. 我将Runnables分成两个不同的元素,由一个开关/案例触发。 However that did not isolate the actions as I thought. 然而,这并没有像我想象的那样孤立行动。

public class MultiThreadingActivity extends Activity { 公共类MultiThreadingActivity扩展Activity {

    public void StartPause1() {
        hand.postDelayed(run1, delay2);
    }

    Runnable run1 = new Runnable() {
        @Override
        public void run() {
            CallFinishedWithResult(threadNumber);
        }
    };
    public void StartPause2() {
        hand.postDelayed(run2, delay2);
    }
    Runnable run2 = new Runnable() {
        @Override
        public void run() {
            CallFinishedWithResult(threadNumber);
        }
    };

} }

I would like the task to be asynchronous, simultaneous and independent. 我希望任务是异步,同步和独立的。

If you want to do things at the same time, AsyncTask is not the right answer. 如果你想同时做事,AsyncTask不是正确的答案。 AsyncTask works by running all tasks in the order they come in on the same thread. AsyncTask的工作原理是按照它们在同一个线程上的顺序运行所有任务。 So task 1 blocks any other task from even starting until its complete. 因此任务1阻止任何其他任务从开始直到完成。 That also means the exact timing of task 2 is indeterminate. 这也意味着任务2的确切时间是不确定的。 If you need multiple tasks at the same time, or you need to tightly control timing, use a Thread instead. 如果您需要同时执行多个任务,或者需要严格控制时序,请改用Thread。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM