Java thread basics-life cycle, create a suitable number of threads, local method security

Thread life cycle

First, let's introduce the general life cycle of threads

Common thread life cycle

Insert picture description here

  1. Initial state: Threads are created (only at the programming language level, the operating system has not yet created real threads), and the CPU is not allowed to allocate resources.
  2. Runnable state: threads can allocate CPU to execute, (threads have been created at the operating system level)
  3. Running state: The operating system assigns it a thread in a running state and occupies CPU usage rights.
  4. Sleep state: In the running state, call the blocking API or wait for a certain condition variable to be established, release CPU usage rights, and fall into a sleep state.
  5. Termination state: The thread will enter the termination state if an exception occurs after the execution of the thread is completed, and the thread life cycle will end.

Java thread life cycle

Insert picture description here
Because the threads in the operating system are very stable, Java has handed over the thread scheduling to the operating system by the JVM. Therefore, Java has merged the runnable state and the running state.

In the dormant state, java has three states: BLOCKED (blocking state), WAITING (no implementation wait), TIMED_WAITING (time-limited wait). When the java thread is in these three states, there is no right to use the CPU.

So how does the state between java threads change?

  1. There is
    only one scenario for the conversion between RUNNABLE and BLOCKED (that is, threads waiting to acquire synchronized implicit locks, synchronized modified methods and code blocks can only be entered by one thread, other threads will fall into BLOCKED, and when the waiting thread acquires synchronized implicit Lock, it will be converted from BLOCKED to RUNNABLE) will trigger this conversion.
    Will the blocking API call transition to the BLOCKED state?
    Answer: No, but at the operating system level, it will transition to the sleep state, the JVM will not change, or RUNNABLE, because the thread scheduling is given to the operating system, waiting for CPU usage rights and waiting for IO in the JVM, both Waiting for CPU usage rights, classified as RUNNABLE.

  2. The transition between RUNNABLE and WAITING
    will trigger three scenarios

    1. Acquire the synchronized implicit lock and call the wait () method. RUNNABLE-> WAITING
    2. Call Thread.join, the thread executing this statement will wait for the Thread thread to finish executing, and the waiting thread will change from RUNNABLE-> WAITING. After the Thread is executed, it will be WAITING-> RUNNALBE.
    3. Thread calling LockSupport.park () the current thread thread will be blocked (from RUNNABLE-> WAITING), calling LockSupport.unpark (Thread thread) can wake up the thread, and the thread state WAITING-> RUNNABLE
  3. The state transition of RUNNABLE and TIMED_WAITING
    will trigger this situation in the five-bell scene (all call methods with timeout parameters)

    1. Call Thread.sleep (long mills)
    2. After obtaining the synchronized implicit lock, call wait (long time).
    3. thread calls Thread.join (long time). Thread is stuck in the timeout and waits for execution (time to continue), and Thread runs.
    4. Call the LockSupport.parkNanos (Object blocker, long deadline) method with timeout parameters;
    5. Call the LockSupport.parkUntil (long deadline) method with timeout parameters.
  4. NEW to RUNNABLE state
    NEW state: Thread thread = new Thread (); will not be scheduled by the operating system.
    RUNNABLE state: thread.start (). Thread scheduling is handed to the operating system (blocking or execution).

  5. From RUNNABLE to TERMINATED termination state
    When the thread finishes executing, it automatically goes from RUNNABLE-> TERMINATED. When an exception is thrown when the run method is executed, it will also enter the termination state.

    Sometimes you want to terminate the thread. The correct posture is to call the interrupt () method, so why not call stop?

What is the difference between stop and interrupt?

The Thread.stop () method will directly terminate the thread and release the corresponding lock.
The interrupt () method simply informs the thread.

  • When the thread is in the WAITING and TIMED_WAITING state, calling the interrupt method will cause the thread to become RUNNABLE, trigger an interruptException at the same time, and clear the interrupt flag bit.
  • When the thread is in RUNNABLE and does not obtain CPU resources (such as blocked in io), it will also throw the corresponding exception.

In the above two cases, the exception is thrown, then we catch the exception through try and catch, and the break can terminate the thread.

  • When the thread is in the RUNNABLE state and has CPU resources, calling the thread.interrupt () method at this time will only notify, and will not throw an exception, only the isInterrupt () method to detect whether the notification is interrupted. Note: __If an exception is thrown, the interrupt flag will be cleared. __You can re-add the flag after try and catch.

How many threads are appropriate

The purpose of our use of multi-threading is to improve the utilization of computer CPU and IO devices.

比如创建两个线程,在一个线程执行CPU计算,另一个线程执行IO操作。这样两者的利用率达到100%。

According to the execution time of CPU and IO, there are two scenarios:

  • IO-intensive: The execution time of the IO device is very long compared to the CPU. The
    optimal number of threads = the number of CPU cores * [1 + (I / O time-consuming / CPU time-consuming)] If the time-consuming ratio of CPU and IO is 1: 2, 3 threads are the most suitable.
  • CPU-intensive: Most of them are pure CPU calculations. In
    theory: number of threads = number of CPUs.

Local variables are thread safe

We all know that the objects from JAVAnew are placed in the shared heap area, and the references are placed in independent stacks.

And each thread has its own independent stack space, and this stack is related to the method call, often called the call stack. For example, method A calls method B. When the program runs, a call stack corresponding to the thread is built, method A is executed, and a space unique to method A is created in the call stack, called a stack frame. When method B is called, the stack frame of the method is created and pushed into the call stack, and when the method ends, the stack frame is popped.

Each thread has its own spatial call stack, each method has its own spatial stack frame in the call stack, and local variables are stored in the stack frame, so you will find that local variables are thread-safe.
Note: set (get () + 1), first press the set method, after pressing get (), the get () method is executed, the stack frame is popped, the return parameter is returned, and the set () method is executed.

Reference geeks time -Java concurrent programming
more visible Deng new

Published 34 original articles · Likes0 · Visits 1089

Guess you like

Origin blog.csdn.net/qq_42634696/article/details/104854573