The profile

CPU speeds have reached tens of billions of calculations per second, or even higher, and home computers have dozens of processes and hundreds of threads to keep their operating systems running properly.

Thread is the basic unit of CPU scheduling and dispatching. In order to make full use of CPU resources and improve productivity and efficiently complete tasks, multithreading is generally adopted in realistic scenarios.

The life cycle of a thread

The life cycle of a thread can be roughly divided into five states: New, RUNABLE, RUNNING, sleep, and DEAD.

1. The new state is the state in which the thread is created and not started. The creation here is only being created at the JAVA programming language level; at the operating system level, the actual threads have not yet been created.

Thread t1 = new Thread()
Copy the code

2. Ready state, which is the thread waiting to be allocated to the CPU after calling the start() method (at this point, the thread has been created at the operating system level)

t1.start()
Copy the code

The state in which the thread executes the Run() method when the CPU is idle

A thread in the running state will switch to sleep if it calls a blocking API or waits for an event

  • Synchronous blocking: The lock is held by another thread
  • Active blocking: Relinquishing CPU execution rights by calling some methods of Thread, such as sleep(), join(), and so on
  • Wait blocking: the wait() method is executed

5. Termination state: the thread enters the termination state when it finishes executing (the run() method finishes executing) or when an exception occurs

These correspond to the six states in the JAVA Thread class State

public class Thread implements Runnable {
   / /...
	
    public enum State {
        NEW, // Initialization state
      
        RUNNABLE, // Running/Running status
      
        BLOCKED, // Block
        
        WAITING, // Wait without time limit
       
        TIMED_WAITING, // There is a time limit for waiting
  
        TERMINATED; // Terminate state
    }
   
    / /...
}
Copy the code

Dormant state (BLOCKED,WAITING,TIMED_WAITING) and RUNNING state conversion

1. Conversion between RUNNING state and BLOCKED state

  • Threads wait for synchronized implicit locks, RUNNING — > BLOCKED

  • The thread obtains a synchronized implicit lock, BLOCKED — > RUNNING

2. Transition between RUNNING state and WAITING state

  • The thread that obtains synchronized implicit locks calls object.wait () without arguments
  • Call the thread.join () method without arguments
  • Call the locksupport.park () method and the thread blocks to a WAITING state,
  • Call the locksupport.unpark () method to wake up the thread and switch from WAITING to RUNNING

3. Transition between RUNNING state and TIMED_WAITING state

  • Calling Thread.. with timeout parameter Sleep (long millis) method
  • A thread that has acquired a synchronized implicit lock calls object. wait(long timeout) with a timeout parameter
  • Call thread.join (Long millis) with the timeout parameter
  • Call the lockSupport. parkNanos(Object Blocker, Long Deadline) method with the timeout parameter
  • Call the locksupport. parkUntil(long deadline) method with the timeout parameter

Deprecated thread methods: Stop (), suspend(), resume()

The stop() method actually kills the thread without giving it any chance to catch its breath. If a thread that has acquired a synchronized implicit lock executes the stop() method at this point, the lock will not be released, resulting in no chance for any other thread to acquire the lock, which is obviously not what we want to see.

The suspend() and resume() methods have also been advised not to be used for unforeseen reasons

You cannot terminate a thread or wake it up using methods such as stop(), suspend(), or resume(), so what should you do instead? The answer is: use the thread.interrupt () method gracefully

The elegant thread.interrupt () method interrupts a Thread

The interrupt() method simply notifies the thread that it has been interrupted by modifying the interrupted status of the calling thread. The thread can detect whether it has been interrupted by using isInterrupted().

When a Thread is blocked, such as by one of object. wait, Thread.join, or thread. sleep; Calling its interrput() method generates InterruptedException.

Expand knowledge

Discover why local variables do not cause concurrency problems

In the Java world, threads can have their own operand stack, program counters, local variable tables, and so on. As we all know, when multiple threads access a shared variable at the same time, it can cause concurrency problems such as data inconsistency. But local variables in Java methods don’t have concurrency problems. Why? Let’s start with the basics.

The scope of a local variable is internal to the method. When the method is finished executing, the local variable is destroyed, which means that the local variable should live and die with the method.

How are methods called in Java? When a method is called, a new stack frame is created and pushed onto the call stack; When the method returns, the corresponding stack frame is automatically popped up. In other words, stack frames and methods live and die together.

From the above we can draw: method call is the process of pushing and pushing, and in Java method local variables are stored in the stack frame, so we use the following diagram to help you understand

Having said that, we haven’t explained why local variables don’t cause concurrency problems. Above, we know that method calls are pushed and pushed (stack frames), and local variables are stored in the stack frame. So what does our thread have to do with the call stack? The answer is: each thread has its own call stack

By now, I believe we have understood that local variables do not have concurrency problems, because each thread has its own call stack, local variables are stored in the call stack of the thread, there is no sharing, naturally there is no concurrency problem.

Welcome to pay attention to the official account: Whiteontheroad, the first time to get the latest information!!