简体   繁体   中英

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. I thought the easiest way to do it was to setup two different Runnables. However if Task 1 < Task 2, and Task 2 is instigated before the end of Task 1, Task 1 shuts Task 2 down.

For the sake of argument, Task 1 is a 5 second delay, Task 2 is a 10 second delay. Task 2 gets trigger 1 second into Task 1. When Task 1 finishes, it appears that Task2 has finished.

threadNumber is an int I set when the task is called to keep track of the results.

They are not acting independent and are being commingled

I broke the Runnables into two distinct elements, triggered by a switch/case. However that did not isolate the actions as I thought.

public class MultiThreadingActivity extends 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 works by running all tasks in the order they come in on the same thread. So task 1 blocks any other task from even starting until its complete. That also means the exact timing of task 2 is indeterminate. If you need multiple tasks at the same time, or you need to tightly control timing, use a Thread instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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