2019 mid-level Android developer interview answers to the article thread

Note: Because the actual development with reference to the answer will be different. Furthermore afraid mislead you, so they still face questions answer themselves to understand! Deep knowledge questions for the interviewer will resume point mentioned, so do not answer back, more understanding.

1. thread pool benefits? Using four kinds of thread pool scene, understand the several parameters of a thread pool?

Reference answer:

The benefits of using the thread pool is to reduce the overhead of creating and destroying threads on the time spent and system resources, to solve the problem of insufficient resources. If you do not use the thread pool, it may cause the system to create a large number of similar threads lead consumed memory or the "over-switching" problem, is summarized

  • Reuse existing threads, reducing object creation, the demise of the cost, good performance.
  • It can effectively control the maximum number of concurrent threads, improve utilization of system resources, while avoiding excessive competition for resources, to avoid clogging.
  • It provides timing executed to perform regular, single-threaded, concurrent control.

Thread pool thread pool .Android Android most common class of thread pool are directly or indirectly to achieve different characteristics by configuring ThreadPoolExecutor having different characteristics are as follows:

  • newCachedThreadPool : Only non-core thread, the maximum number of threads is very large, it creates a new thread for a new job when all threads are active, otherwise it will make use of idle threads (60s idle time, after will be recycled, so the thread pool have 0 the thread may) to handle the task.
    • Advantages: Any task will be executed immediately (SynchronousQuue task queue corresponding to an empty set); Comparative adapted to perform a lot less time consuming task.
  • newFixedThreadPool : only the core thread, and a fixed amount of time all threads are active, because there is no limit the size of the queue, waiting for a new task will be executed when the thread pool idle worker threads are not released, it will take up some system resources.
    • Advantages: faster response to outside request
  • newScheduledThreadPool : core number of threads fixed, non-core thread (not a job will be idle immediate recovery) is not limited.
    • Advantages: the task and repeating the task execution timing of a fixed period
  • newSingleThreadExecutor : only one core thread to ensure that all tasks are completed in sequence in the same thread
    • Pros: do not need to deal with the problem of thread synchronization

By Source can understand the above four thread pool is actually still use ThreadPoolExecutor class implements
Here Insert Picture Description
2.Android also easy to see which thread switching classes?

Reference answer:

  • AsyncTask: thread pool bottom package and Handler, easy to perform background tasks and operations performed in the sub-UI thread.
  • HandlerThread: message in a thread has a loop, which can be used inside Handler.
  • IntentService: is an asynchronous, it will automatically stop the service, internal use HandlerThread.

3. talk about the principle of AsyncTask

Reference answer:

  • There are two AsyncTask thread pools (SerialExecutor and THREAD_POOL_EXECUTOR) and a Handler (InternalHandler), wherein the thread pool SerialExecutor for queuing task, while the thread pool THREAD_POOL_EXECUTOR for actually performing the task, InternalHandler execution environment for the switching from the thread pool to the main thread.
  • sHandler is a static Handler object, in order to be able to switch to the main thread execution environment, which requires sHandler the object must be created in the main thread. Because static members will be initialized when the class is loaded, so this requires AsyncTask disguise the class must be loaded in the main thread, otherwise it will not work with a process AsyncTask.

4.IntentService what's the use?

Reference answer:

IntentService be used to perform time-consuming background tasks to perform when the task is completed will automatically stop, and because IntentService is why the service, unlike ordinary Service, IntentService can automatically create sub-thread to perform tasks, which leads to its priority than simply the thread must be high, not easy to be killed by the system, so IntentService more suitable for the implementation of a number of high-priority background task.

5. Create a thread with a thread to create a distinction between the service directly in an Activity?

Reference answer:

  • It was created in the Activity : The Thread is for this Activity services, complete the specific task of Activity accountable, proactive notification, the Activity some news and events, meaning after the destruction of Activity, which did not survive the Thread.
  • Service was created in the middle : This is the only way to ensure the longest life cycle of Thread, as long as the entire Service does not exit, Thread can always performed in the background, usually created in onCreate Service's (), the destruction in onDestroy () in. Therefore, the creation of the Service Thread, suitable for long-term implementation of some background tasks independent of the APP, more common is: to keep the server in the Service of the long connection.

6.ThreadPoolExecutor strategy work?

We will follow the following rules ThreadPoolExecutor perform tasks: Reference answer

  • If the number of threads in the pool does not reach the number of kernel threads, it will directly start a kernel thread to perform tasks
  • If the number of threads in the pool has reached or exceeded the number of kernel threads, then the task will be inserted into the task queue queued for execution.
  • If you can not be at the 2:00 task into the task queue, it is often because the task queue is full, this time if the maximum number of threads in the thread pool does not meet the requirements, then immediately starts a thread to perform non-core tasks.
  • If the third point has reached the maximum number of threads in the thread pool specified, then refused to carry out this task, ThreadPoolExecutor calls rejectedExecution RejectedExecutionHandler method to notify the caller

7.Handler, Thread and HandlerThread difference?

Reference answer:

  • Handler : android responsible for sending and processing messages, you can implement the message communication between the main thread and other threads branch through it.
  • The Thread : minimum unit of the Java execution process operation, i.e., the basic unit of processor performs scheduling. A process running the program all the way alone.
  • HandlerThread : HandlerThread a class inherits from Thread no Thread for Java in Android in any package, but to provide a class inherited from Thread HandlerThread class, this class of Java Thread do a lot of convenient package. HandlerThread inherited from Thread, so it is essentially a Thread. The difference is that ordinary Thread, Looper directly realized its in-house, this is the essential message mechanism Handler. Have their own looper, it allows us to distribute and process messages in its own thread. If you do not HandlerThread then need to manually call Looper.prepare () and Looper.loop () methods.

8.ThreadLocal principle

Reference answer:

ThreadLocal class is about creating a thread-local variables. Usage scenario as follows:

  • Singleton and implement a single thread context information stored in a single thread, such as transaction id and the like.
  • Achieve thread-safe, non-thread-safe objects will become thread-safe after use ThreadLocal, because each thread has a corresponding instance. Some thread-related data bearer, to avoid back and forth in the method to pass parameters.

When you need to use multiple threads, there is no need to share variables happens, then you do not have much trouble using the synchronized keyword to lock, each thread is equivalent to open up a space in the heap memory, with a shared thread buffer variable by variable shared heap buffer memory and read operations, the memory corresponding to the ThreadLocal thread, a local variable. Each time data can be read and manipulate the thread itself, does not need to interact with a main memory buffer by a variable. It does not modify the main memory data copied to the working memory within the thread again as synchronized as main memory data. ThreadLocal allows the thread from monopolizing resources, stored in the internal thread, the thread to avoid congestion caused by CPU throughput decreases.

Thread contained in each one ThreadLocalMap, ThreadLocalMap ThreadLocal object is the key, value is exclusive data.

9. Is multithreading will be efficient (strengths and weaknesses)

Reference answer:
the advantages of multi-threading:

  • Convenient and efficient shared memory - shared memory multi-process more inconvenience, and will offset the benefits of multi-process programming
  • Lighter context switching overhead - without switching address spaces, do not change the CR3 register, do not empty the TLB
  • After the implementation of tasks on the thread is automatically destroyed

Multithreading disadvantages:

  • Open thread needs to take up some memory space (by default, each thread has a market share 512KB)
  • If you open a large number of threads, it will take up a lot of memory space, reducing the performance of the program
  • The more threads, cpu overhead on the calling thread is greater
  • Programming more complex, such as inter-thread communication, multi-threaded data sharing

Draw on comprehensive, multi-threading may not be able to improve efficiency, but is a burden in the memory space is tight situation, so the daily development, should be

  • Do not frequently create, destroy threads, use the thread pool
  • Reduce inter-thread synchronization and communication (most critical)
  • Avoid the need for frequent write shared data
  • Arrange shared data structure, to avoid false sharing (false sharing)
  • Nonblocking data structures / algorithms
  • Avoid scalability issues may arise system calls (such as mmap)
  • To avoid a large number of missing page exception try to use Huge Page
  • If you can use lightweight threads instead of user-mode kernel threads

10. The multi-threaded, so that you make a single example, how would you do

Reference answer:

  • Factors considered in establishing the single mode, multi-threading embodiment, there are many, such as thread-safe - Load Delay - Code Security: such as prevention of the attack sequence, the reflection preventing attacks (private method calls for preventing reflection) - Performance Factors
  • There are many implementations, starving, lazy (thread-safe, non-thread-safe), double-checked (DCL), inner classes, and enumerations

11. In addition to notify What better way to wake up the thread

Reference answer:

  • When a thread calls have the Object lock wait () method, it will cause the current thread to join object.wait waiting queue and release the lock Object currently occupied, so that other threads have the opportunity to acquire the lock Object, Object obtain locks thread calls notify () method, you can wait in the queue Object.wait random wake up one thread (the wake random regardless of the order added, high priority will be awakened high probability)
  • If you call notifyAll () method wakes up all the threads. Note: After calling notify () method does not immediately release the object lock, the thread will wait for the release of finished Object lock.

12. What is ANR? What happens ANR? How to avoid? Without looking at the code of how to quickly locate the problem occurs ANR?

Reference answer:

  • ANR (Application Not Responding, the application not responding): When the operating system can not handle a period of time, will be at the system level ANR dialog box will pop up
  • ANR may be generated because there was no response to user input events within 5s, BroadcastReceiver does not end within the 10s, in the 20s did not end Service
  • ANR do not wish to avoid doing time-consuming operations in the main thread, but such as inheritance Thread opened by the child thread, method, or implement Runnable, use AsyncTask, IntentService, HandlerThread etc.

Threads to this chapter is over, Android needs more study material can follow my homepage relevant
Here Insert Picture Description
today updated Video: Android Native

What JNI Yes.
Native method to register.
JNI data type conversion.
Native how to communicate with Java.

Guess you like

Origin blog.csdn.net/Android_SE/article/details/91993979