Android Combat 43: Terminate a thread caused by

Source: Internet
Author: User

This is a veteran face test. Usually the interviewer will ask you about the Java thread and then ask this question.
From theory to practice, this is a good path.
A thread is a way for the operating system to implement multitasking, and it can be understood that a thread is the execution unit of a task. For example, every app in the Android system has its own main thread, and you can create a worker thread "parallel" to work for us.

Methods for creating new threads in Java

Java provides language-level support for threading (thread) (relying on virtual machines). With the thread class and runnable interface under the Java.lang package, you can complete the task of creating a new thread.
1. Extends Thread class

Private  class numbercountthread extends Thread {         Public void Run() { for(inti =0;i< +* +; ++i) {LOG.D (TAG,"Count:"+i);if(Mthread.isinterrupted ()) {LOG.D (TAG,"Interrupted, return!");return; }Try{Thread.Sleep ( +); }Catch(Interruptedexception e)                {E.printstacktrace (); }            }        }    }

2, implements runnable interface

private   Class  numbercountrunnable  implements  Span class= "Hljs-title" >runnable  { public  void  run  () {int  i = 0 ; while  (true ) {LOG.D (TAG,  "Count:"  + i); try  {Thread.Sleep (1000 ); } catch  (interruptedexception e) {e.printstacktrace (); } i++; } } }

3. Start them

Thread mThread;//Thread        =new NumberCountThread();        mThread.start();//Runnable        =newThread(new NumberCountRunnable());        mThread.start();
Running state of Java threads

1, new, create one thread
2, Runnable, called the Start method after the thread is ready to wait for the use of the CPU.
3, Running, the thread is officially running, execute the code in run.
4, Blocked, blocking state in several cases: Call the Wait method, the thread gets the synchronization lock of the object, call the sleep or join method, make an IO request.
5, Dead, the execution of the thread, or other reasons to exit the Run method, the end of the life cycle.

Terminating a thread

Looking at the thread dead state, you will automatically end the life when the thread finishes executing. This leads to common method one, thread tagging.
In the above two examples, we put a Boolean tag in the loop body, and when it is false, stop the loop and let the thread execute.
Like what:

Private BooleanMthreadflag =true;Private  class numbercountthread implements Runnable {         Public void Run() {inti =0; while(Mthreadflag) {LOG.D (TAG,"Count:"+ i);Try{Thread.Sleep ( +); }Catch(Interruptedexception e)                {E.printstacktrace ();            } i++; }        }    }

In another case, a thread simply executes a single, time-consuming task, and the method fails. The Stop method in a thread is deprecated, so what can I do to stop it?
It is now "interrupted" using the interrupt method, which immediately exits the run method and enters the dead state.

Synchronizing with the UI thread

1. Handler + Message
Reference: Android Combat tip 38: Memory leaks that may be caused by handler use

2. View.post method
When reading a picture in asserts, use a thread, then post directly to the main thread.

try  {  InputStream InputStream = Getresources (). Openrawresource (R.ID.XXX);     InputStream InputStream = Assetmanager.open ( "android/xxx.png" ); final     Bitmap Bitmap = Bitmapfactory.decodestream (InputStream); Mmainlayout.post (new  Runnable () { @Override  public  void              Run  () {log.d (TAG, );        Mmainlayout.setbackground (new  bitmapdrawable (bitmap));    }    }); Inputstream.close ();} catch  (IOException e) {E.printstacktrace ();}  

Reference:
http://blog.csdn.net/huang_xw/article/details/7316354
Http://www.cnblogs.com/riskyer/p/3263032.html

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Android Combat 43: Terminate a thread caused by

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.