The overall picture is started by AsyncTask in the onPreExecute method, preparation is performed. Then in doInBackground , inside which sequentially runs thread by thread in newSingleThreadExecutor() and when all threads run in newSingleThreadExecutor() then doInBackground finishes its execution, the last onPostExecute method is onPostExecute in which I write to the user that everything went well.

The question is, will doInBackground really wait for newSingleThreadExecutor() inside it to execute all its threads?

Here is the code how it works for me

 new AsyncTask<Void, Void, Void>() { MyDialog dialog; @Override protected void onPreExecute() { super.onPreExecute(); dialog = MyDialog.newInstance(R.layout.activity_good_job_dialog); dialog.show(getFragmentManager(), "dialog"); } @Override protected Void doInBackground(Void... params) { ExecutorService pool = Executors.newSingleThreadExecutor(); pool.submit(new ZipUtil()); pool.submit(new Runnable() { @Override public void run() { sentPhoto(); } }); pool.submit(new Runnable() { @Override public void run() { closeCamera(); stopBackgroundThread(); dialog.dismiss(); } }); pool.shutdown(); return null; } @Override protected void onPostExecute(Void aVoid) { super.onPostExecute(aVoid); startActivity(new Intent(getApplicationContext(), SuccessActivity.class) .setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK)); } }.execute(); 

    1 answer 1

    doInBackground will not wait for other threads running inside it. It will start them and the onPostExecute call will immediately follow, but the threads running in the doInBackground will still do their work. Why should you run a separate thread in doInBackground if it is already a separate thread, especially if the threads are running in newSingleThreadExecutor, i.e. the threads you create will be executed in turn in one. If I were you, I would simply call methods in the doInBackground consistently, without creating separate threads for execution in the doInBackground.

    • But in my example, visually for the user, the code runs much faster since the user does not wait for execution in the doInBackground . And in general, the order is maintained ... But I have a question according to your answer, why doesn’t the newSingleThreadExecutor die, if, as you say, the doInBackground that caused it has already finished its execution and has died? - Aleksey Timoshchenko
    • correctly, which is faster, but in onPostExecute you tell the user that everything went well, but in fact it is not. And to the question why the newSingleThreadExecutor does not die, please provide its code. - Yury Pashkov
    • Added, ....... - Aleksey Timoshchenko
    • I read that even if the method is already completed, but the threads generated by it are still being executed, the system will wait for them to complete. - Yury Pashkov