Java Multithreading

Difference between Thread and Runnable

  • Thread implements the Runnable interface, allocates CPU resources before executing multithreading, checks whether the thread is started, etc., and then executes the thread.
  • Runnable is suitable for multiple threads of the same program code to process the same resource.
  • The Runnable interface avoids the limitations of Java's single inheritance.
  • Runable increases the robustness of the program, code can be shared by multiple threads, data and code are independent.

thread state

Five states: Created, Ready, Running, Blocked, Terminated.

The thread will not start immediately after using start(), but is in the ready state, waiting for the CPU to schedule before starting.


difference between process and thread

  • Threads are divided on a process basis.
  • The thread disappears and the process continues. The process disappears and the thread ends.
  • A process is the basic unit of program operation and resource allocation. A program has at least one process, and a process has at least one thread.
  • A thread is the entity of a process, the basic unit of CPU scheduling and dispatch, and a basic unit smaller than a program that can run independently.

Two ways to implement multithreading

  • Inherit Thread
  • Implement the Runnable interface

thread start

Completed by the start() method, CPU scheduling is required, and calling start() is actually the run() method.


thread terminated

  • stop(), prone to problems, obsolete
  • Volatile variables are used as control conditions to control thread execution.
  • interrupt to terminate the thread in sleep() wait() and other states.
  • Threads can also be terminated with Future's cancel method.

In multi-threading, it is recommended to use the Runnable interface to implement, which can avoid the development limitations caused by single inheritance, and use the Runnable interface to achieve the purpose of resource sharing.


Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325562519&siteId=291194637