Does the Activity close the child thread along with it?

Question: When a page (Activity) is closed during development, are the threads in it closed?
Answer: No (tested)
When you need to close the thread when the activity is closed in development:
1. You can set the mark in the Run method of the thread to close it manually. (Use the stop mark bit, then you can keep it true Completely run before stopping)
2. It is also possible to call the Thread.stop() method, but there will be a problem (use the Thread.stop method to stop the thread, it is not guaranteed whether the thread is completely run once)
Test code:
package com.example .testthread;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.util.Log;
public class MainActivity extends AppCompatActivity {
    Thread thread;
// private Handler handler = new Handler(){
// @Override
// public void handleMessage(Message msg) {
// super. handleMessage(msg);
//            Log.i("TAG", "handler");
//        }
//    };


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    }


    @Override
    protected void onResume() {
        super.onResume();
        thread = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i <4 ; i++) {
                    Log.i("TAG", "Thread"+i);
                    try {
                        Thread.sleep(4000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
//                handler.sendEmptyMessage(0);
                Log.i("TAG", "Thread");
            }
        });
        thread.start();
        Log.i("TAG", "onResume");
        finish();
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        thread.stop();
        Log.i("TAG", "onDestroy");
    }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326074921&siteId=291194637