There are two ways to implement multithreading: one is to inherit thread, and the other is to implement Runnable interface. The latter is recommended because Java is single inheritance. If you inherit thread, you cannot inherit other classes. RUnnable is obviously a little more flexible.

Implement Runnable with advantages over Thread:

  • Avoid limitations due to Java single inheritance.
  • Thread better describes the concept of data sharing than inheriting thread.

Whether it implements Runnable or inherits Thread methods to implement multithreading, it starts from start, not run. If run is called, the code block inside the run method is actually executed in the current thread.

Reason: When starting a thread, the operating system will allocate resources to it. In the start method, it not only executes multi-threaded code, but also calls start0 method, which is declared as native. In Java language, there is a technology called JNI, namely JavaNativeInterface. This technique is characterized by calling functions provided by the native operating system, but has the disadvantage of not being able to leave the particular operating system. If a thread needs to execute, the operating system must allocate resources, so this operation is implemented by the JVM depending on the operating system.

If thread threading is implemented by implementing Runnable, the difference is that Runnable does not have a start method, and multithreading must be started by the start method. So we have to call Thread(RUnnable Target), a constructor of the Thread class. This constructor gets an implementation of the RUnnable interface, so we can start multithreading by calling start.

Message mechanism mainly refers to the operation mechanism of Handler. Its operation needs the support of MessageQueue and Looper at the bottom level. MessageQueue provides external insertion and deletion work in the form of queue.

Implement Runnable

class MyRUnnable() : Runnable {
    override fun run() {/ /... Val MSG: Message = message.obtain () handler.post(MSG)}}Copy the code

Start multithreading

val thread = Thread(MyRunnable())
thread.start()
Copy the code

Handle multithreaded returns

val handler = object: Handler() { override fun handlerMessage(msg: Message?) { msg? .let { ///... Logic code}}}Copy the code