Java multithreading core knowledge sharing necessary for job-hopping interview

As a Java developer, multi-threading is an inescapable topic, whether it is work or interview, but it is more vague and difficult to understand, because multi-threaded programs are more difficult to observe and track when they are running. Understand the knowledge of multithreading and concurrency, you can open up the gap with the people around you during the interview, and you can know it well when you code. So I wrote this article based on the problems encountered in my work and how to use it.

I have also compiled some frequently asked interview questions here. Friends in need can click the link below to get them for free!
Link: 1103806531 Password: CSDN

Insert picture description here

1. Process

The process is the foundation of the operating system structure; it is the execution of a program; it is the activity that occurs when a program and its data are executed sequentially on the processor. In the operating system, almost all running tasks correspond to a process (Process). When a program enters the memory and runs, it becomes a process. A process is a program in the running process and has a certain independent function. A sentence describing the process is very classic-a process is an independent unit of the system for resource allocation and scheduling.

A process is an independent entity in the system, with its own independent resources and its own private address space. The essence of the process is the one-time execution process of the program in the multi-program system. It is dynamically generated, dynamically dying, and has its own life cycle and various states. The process is concurrency, it can execute concurrently with other processes, and move forward at independent and unpredictable speeds.

( Note : Concurrency and parallelism are different. Parallel refers to multiple instructions running on multiple processors at the same time. Concurrency refers to the execution of only one instruction at the same time. But multiple process instructions are executed in rapid rotation, and it looks like multiple instructions are executed at the same time.)

The process is composed of three parts: program, data and process control block.

Two, thread

A thread, sometimes referred to as a Lightweight Process (LWP), is the smallest unit of program execution flow. A standard thread is composed of thread ID, current instruction pointer (PC), register set and stack. In addition, the thread is an entity in the process and is the basic unit independently scheduled and dispatched by the system. The thread itself does not own system resources, but only has a few essential resources in operation, but it can be combined with other processes that belong to the same process. Threads share all the resources owned by the process. A thread can create and cancel another thread, and multiple threads in the same process can execute concurrently. Due to the mutual restriction between threads, the threads are intermittent in operation. Every program has at least one thread. If the program has only one thread, it is the program itself.

A thread is a single sequential control flow in a program. Running multiple threads at the same time to complete different tasks in a single program is called multithreading.
  
In Java Web, it should be noted that threads are at the JVM level. Without stopping, they die together with JVM, that is, if a Web service starts multiple Web applications, a certain Web application starts a certain thread, if it is closed For this web application, the thread will not be closed because the JVM is still running, so don’t forget to stop the thread when the web application is closed.

Three, thread status

Insert picture description here

The thread includes the following 5 states.

  1. New state (New) : After the thread object is created, it enters the new state. At this time, it is the same as other Java objects, only memory is allocated by the Java virtual machine and its member variable values ​​are initialized.

  2. Ready state (Runnable) : Also called "executable state". The thread object is called the start () method of the object, the thread is in the ready state. The Java virtual machine creates a method call stack and a program counter for it. A thread in the ready state may be scheduled for execution by the CPU at any time, depending on the scheduling of the thread scheduler in the JVM.

  3. Running status (Running) : The thread obtains CPU permissions for execution. It should be noted that the thread can only enter the running state from the ready state.

  4. Blocked : A blocked state is a thread giving up CPU usage rights for some reason and temporarily stopping running. Until the thread enters the ready state, it has a chance to go to the running state. There are three types of blocking:
    (01) Waiting for blocking-by calling the wait() method of the thread, the thread waits for the completion of a certain job.
    (02) Synchronous blocking-If the thread fails to acquire the synchronized synchronization lock (because the lock is occupied by other threads), it will enter the synchronized blocking state.
    (03) Other blocking-By calling sleep() or join() of the thread or issuing an I/O request, the thread will enter the blocking state. When the sleep() state times out, join() waits for the thread to terminate or time out, or the I/O processing is completed, the thread turns to the ready state again.

  5. Dead state (Dead) : The thread finishes execution, exits the run() method due to an exception, or directly calls the stop() method of the thread (it is easy to cause deadlock, and it is not recommended now), and the thread ends its life cycle.

Four, wait(), notify(), nofityAll() methods

In Object.java, methods such as wait(), notify() and notifyAll() are defined.

The function of wait() is to let the current thread enter the waiting state. At the same time, wait() will also let the current thread release the lock it holds.

The function of notify() and notifyAll() is to wake up the waiting threads on the current object; notify() is to wake up a single thread, and notifyAll() is to wake up all threads.

The detailed information about the wait/wake-up API in the Object class is as follows:
  notify()-wake up a single thread waiting on this object monitor to enter the "ready state".  
  notifyAll()-wake up all threads waiting on the monitor of this object to enter the "ready state".
  wait()-Let the current thread be in a "waiting (blocking) state", "until other threads call the notify() method or notifyAll() method of this object", the current thread is awakened (into the "ready state").
  wait(long timeout)-Let the current thread be in a "waiting (blocking) state", "until other threads call the notify() method or notifyAll() method of this object, or the specified amount of time is exceeded", the current thread is awakened (enter "Ready state").
  wait(long timeout, int nanos) – Let the current thread be in a "waiting (blocking) state", "until other threads call the notify() method or notifyAll() method of this object, or some other thread interrupts the current thread, or has Exceeding a certain actual amount of time", the current thread is awakened (into the "ready state").

The role of wait() is to make the "current thread" wait (the lock will be released), and the "current thread" refers to the thread running on the cpu!

Five, thread priority and daemon thread

1. Thread priority

The thread priority in java ranges from 1 to 10, and the default priority is 5. The default priority of each thread has the same priority as the parent thread that created it. By default, the mian thread has normal priority. "High priority threads" will be executed prior to "low priority threads". Thread provides setPriority(int newPriority) and getPriority() methods to set and return thread priority.

The Thread class has 3 static constants:

——MAX_PRIORITY = 10

——MIN_PRIORITY = 1

——NORM_PRIORITY = 5

2. Daemon thread

There are two kinds of threads in java: user threads and daemon threads. They can be distinguished by the isDaemon() method: if it returns false, the thread is a "user thread"; otherwise, it is a "daemon thread".
User threads generally perform user-level tasks, while daemon threads are "background threads" that are generally used to perform background tasks. It should be noted that the Java virtual machine will exit after the end of the "user thread".

The daemon thread is also called "background thread" or "elf thread". It has a feature-if all foreground threads die, background threads die automatically.

Set a thread by setDaemon(true).

At last

Hope this article is helpful to everyone!

I have also compiled a complete set of video tutorials for architects and systematic materials on java, including java core knowledge points, interview topics, and the latest 20 years of Internet real questions and e-books.

Friends in need can click the link below to get it for free!
Link: 1103806531 Password: CSDN

Insert picture description here
Insert picture description here

Guess you like

Origin blog.csdn.net/XingXing_Java/article/details/108588900