Talking about the concept and basic usage of multi-threading summary

This article first briefly introduces the basic concepts of multithreading, and the specific in-depth introduction will be introduced later.

1. What is multithreading? Why use multithreading?

  Before introducing multithreading, we need to introduce threads, and we need to introduce threads without processes.

  First  process: is a program in execution, each process execution has an execution order, which is an execution path, or a control unit;

  Thread: It is an independent control unit in the process, and the thread controls the execution of the process. There is at least one process within a process.

     Multithreading: There is more than one thread in a process.

   Why use multithreading: In order to make better use of cpu resources, if there is only one thread, the second task must wait until the end of the first task. If multithreading is used, it can be executed while the main thread is executing the task Other tasks do not need to wait, so all multithreaded code can be implemented with a single thread.

  

Second, the life cycle of the thread:

  • New: The state from the creation of a new thread object to the thread of the program start() is the new state;
  • Ready: After the thread object calls the start() method, it is in a ready state and waits for the scheduling of the thread scheduler in the JVM;
  • Running: The thread in the ready state can execute run() after acquiring the CPU resources. At this time, the thread is in the running state, and the thread in the running state can be in three states: ready, blocked, and dead.
  • Waiting/blocking/sleep: After a thread executes methods such as sleep (sleep), suspend (suspend), it will lose its occupied resources, thus entering the blocking state, and can re-enter the ready state after the sleep is over.
  • Termination: A transition to the terminated state occurs when the run() method completes or when another termination condition occurs.

Third, the method of creating a thread:

  1. Inherit the Thread class:

  2. Implement the Runnable interface:

  3. Create threads through Callable and Future:

------------------------To know what's going on in the future, please allow me to rest for a while -------------- ------

Fourth, the difference between inheriting the Thread class and implementing the Runnable interface.

Five, thread synchronization.

6. Communication between threads, waiting for the wake-up mechanism.

 

 

 

Guess you like

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