Android Development Practice: Dealing with multithreading in a "professional" manner

Source: Internet
Author: User

When I first started learning a programming language, I always had a puzzle about how to make my Code look "professional". Many times, we can follow the textbook to achieve some basic functions, such as the use of a socket to send/receive a few characters, write a thread to complete an asynchronous task, but in the actual project, often not so simple, such as the need to design the socket communication protocol, the need to handle the socket connection abnormal disconnection, Need to consider the situation of the thread blocking the normal exit and release of resources, and so on, about these "combat experience", the previous article is also involved in the future, ready to open a topic to share with you to discuss, today first simply say how to more "professional" in the Android program to deal with multi-threaded.


The following is assumed to implement a simple scheduled task, print a log message per second, see the implementation of such a multithreaded program, what needs to be noted, the key points are added to the code in the form of annotations.


Package com.ticktick.testthread;                Import Android.util.Log;    public class Printthread implements Runnable {private Thread mthread;    Private Boolean misthreadstarted = false; Private volatile Boolean misthreadexit = false; Key 1: Defines a volatile type of condition variable that is used for thread exit public void Startprintthread () {if (MI        sthreadstarted) {return;        } Misthreadexit = false; Mthread = new Thread (this);             Key 2: The new Thread object is recreated each time it is started, because a thread can only be Mthread.start () by the start one time;                             Misthreadstarted = true;    LOG.D ("Printthread", "Timer Started"); } public void Stopprintthread () {if (!misthreadstarted) {RET        Urn } Misthreadexit = true; Key 3: Notifies the thread to exit the Loop Mthread.interrupt (); Key 4: Call interrupt to prevent the thread from being in a blocking state such as sleep or wait//But note that for SOcket.accept such a blockage, thread.interrupt is no way, but you can use Socket.close to wake up the try { Mthread.join (1000); Key 5: Call join, wait for thread to really complete exit, suggest a wait timeout} catch (Interruptedexception e) {e.printstacktrace ()        ;                             } misthreadstarted = false;    LOG.D ("Printthread", "Thread Stopped");    } public boolean isthreadstarted () {return misthreadstarted; } @Override public void Run () {LOG.D ("Printthread", "Thread run Enter                             !");                                     while (!misthreadexit) {log.d ("Printthread", "Thread arrived!");            try {thread.sleep (1000);//Key 6: In thread looping, it is recommended to use sleep to allow other threads to compete cpu,sleep (0) to represent the immediate re-competition of the CPU } catch (Interruptedexception e) {e.printstacktrace ();//You can jump right outLoop, or you can ignore it and check again for the condition variable Misthreadexit}} log.d ("Printthread",    "Thread Run Exit!"); }                 }


In fact, not only the Java thread, C + + multithreading should also pay attention to these key points, here to summarize:


(1) To define a volatile type of condition variable, decide whether to exit the thread's dead loop


(2) in a thread loop, it is best to have a sleep delay function that gives other threads a chance to compete for CPU


(3) To stop thread execution, there are three things to do, 1. The conditional variable to exit the set thread; 2. The blocking in the thread is awakened by a call like interrupt or socket.close; 3. Through the Join function, wait for the thread to actually exit before releasing other related resources


Once in the project, without a join waiting for the thread to exit, so often in the software exit the time inexplicably crash, therefore, now pay extra attention to this point, and the habitual thread end of the place to print debugging information to ensure that all the threads that are open in the program are destroyed normally.


About the processing of the thread to share here, hope to help beginners, have any questions welcome message or letter [email protected] exchange.


This article is from the "Shadow Three People" blog, please be sure to keep this source http://ticktick.blog.51cto.com/823160/1410697

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.