How does Android stop thread and asynctask?

Source: Internet
Author: User

From: http://www.android-study.com/jichuzhishi/376.html

We know that there is no way to stop a running thread in the Java thread, and the same is true in asynctask of Android. To stop a thread, we can set a flag in this thread, then, the key step in the thread run method or the doinbackground method of asynctask is used to determine whether to continue the execution. Then, change the flag where the thread needs to be terminated to stop the thread.

The cancel method that calls asynctask externally cannot stop a started asynctask. The cancel method is similar to the thread's interrupt method. After a thread's interrupt method is called, the thread still runs, however, if the thread's run method is in sleep or wait status after calling sleep or wait, sleep and wait will immediately end and interruptedexception will be thrown. The Cancel Method of asynctask is the same. If the sleep or wait method is called in the doinbackground method of the task, after the Cancel Method of the task instance is called in the UI thread, sleep or wait ends immediately and an interruptedexception exception is thrown. However, if there is other code behind the code that captures the exception, the code will continue to be executed. The test code is as follows:

 

package eoe.task; import android.app.Activity;import android.os.AsyncTask;import android.os.Bundle;import android.util.Log;import android.view.View;import android.view.View.OnClickListener;import android.widget.Button; public class AsyncTaskTest extends Activity {    /** Called when the activity is first created. */     @Override    public void onCreate(Bundle savedInstanceState) {        super.onCreate(savedInstanceState);        setContentView(R.layout.main);        // set the six buttons listener        Button startButton = (Button) this.findViewById(R.id.StartTask);        final TestAsyncTask task = new TestAsyncTask(0);        startButton.setOnClickListener(new OnClickListener() {            public void onClick(View v) {                task.execute("str1", "str2");            }        });        Button endButton = (Button) this.findViewById(R.id.StopTask);        endButton.setOnClickListener(new OnClickListener() {            public void onClick(View v) {                task.cancel(false);            }        });         Button startSleepButton = (Button) this                .findViewById(R.id.StartThread_sleep);        final ThreadForTestSleep threadForTestSleep = new ThreadForTestSleep();        startSleepButton.setOnClickListener(new OnClickListener() {            public void onClick(View v) {                threadForTestSleep.start();            }        });         Button endSleepButton = (Button) this                .findViewById(R.id.StopThread_sleep);        endSleepButton.setOnClickListener(new OnClickListener() {            public void onClick(View v) {                threadForTestSleep.interrupt();            }        });         Button startWaitButton = (Button) this                .findViewById(R.id.StartThread_wait);        final ThreadForTestWait threadForTestWait = new ThreadForTestWait();        startWaitButton.setOnClickListener(new OnClickListener() {            public void onClick(View v) {                threadForTestWait.start();            }        });         Button endWaitButton = (Button) this.findViewById(R.id.StopThread_wait);        endWaitButton.setOnClickListener(new OnClickListener() {            public void onClick(View v) {                threadForTestWait.interrupt();            }        });    }     /**     * AsyncTask     *     * @author alex     *     */    private class TestAsyncTask extends AsyncTask<String, Integer, Double> {        double a;         public TestAsyncTask(double a) {            this.a = a;        }         @Override        protected Double doInBackground(String... params) {            for (String param : params) {                Log.i("TestAsyncTask", "param:" + param);            }            Log.i("TestAsyncTask", "doInBackground is start");            for (int i = 0; i < 10000000; i++) {                a = i * i + i;                Log.d("-----", "a:" + a);            }            Log.i("TestAsyncTask", "sleep 1 is end");            try {                Thread.sleep(30000);            } catch (InterruptedException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }            Log.i("TestAsyncTask", "sleep 2 is end and continue execute");            return a;        }         protected void onPostExecute(Double result) {            Log.i("last a value is", "" + result);        }    }     /**     * test sleep     *     * @author Administrator     *     */    private class ThreadForTestSleep extends Thread {        public void run() {            Log.i("ThreadForTestWait", "sleep start");            try {                sleep(30000);            } catch (InterruptedException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }            double a;            for (int i = 0; i < 10000000; i++) {                a = i * i + i;                Log.d("-----", "a:" + a);            }            Log.i("ThreadForTestWait", "sleep end");        }    }     /**     * test wait     *     * @author Administrator     *     */    private class ThreadForTestWait extends Thread {        public void run() {            Log.i("ThreadForTestWait", "wait start");            try {                synchronized (this) {                    wait();                }            } catch (InterruptedException e) {                // TODO Auto-generated catch block                e.printStackTrace();            }            Log.i("ThreadForTestWait", "wait end");        }    }}

Let's take a look at this example. Here we mainly use the view. View. onclicklistener; listener, Android. widget. Button button. We define a button as start and a button as stop. In this way, we can add a listener to the button and define in the listener that when the button is clicked, we can stop asynctask and thread. I personally feel very good about this method. This mainly adds a sleep (30000); in this way, we have time to determine whether we should do anything.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.