preface

Welcome to our GitHub repository Star: github.com/bin39232820… The best time to plant a tree was ten years ago, followed by now. I know many people don’t play QQ anymore, but for a moment of nostalgia, welcome to join the six-vein Shenjian Java rookie learning group, group chat number: 549684836 encourage everyone to write blog on the road of technology

omg

Multithreaded series has written a lot in front, interested can go to my warehouse Kangkang, today? I also see people write good, and then their own plagiarism, ha ha, in fact, is to see the knowledge of the record. If you write it yourself, you might remember it better.

Thread state transition diagram

  • NEW Initial state
  • RUNNABLE Running status
  • BLOCKED state
  • WAITING state
  • TIME_WAITING Indicates the timeout waiting status
  • TERMINATED state

Note: The thread calling obj.wait() needs to fetch obj’s monitor first, and wait() releases obj’s monitor and enters the wait state. Synchronized is synchronized with wait() and notify().

The difference between blocking and waiting

Blocking: When a thread attempts to acquire an object lock (a lock in a non-java.util.concurrent library, known as synchronized) that is held by another thread, the thread is blocked. It is characterized by simplicity of use and the decision of the JVM scheduler to wake itself up, rather than the need for another thread to explicitly wake itself up without responding to interrupts.

Blocking The state of a thread waiting for a lock to be blocked in a critical region

Wait: When a thread is waiting for another thread to notify the scheduler of a condition, that thread enters the wait state. It is characterized by the need to wait for another thread to explicitly wake itself up, and its implementation is flexible, semantically rich, and can respond to interrupts. For example, call object.wait (), thread.join (), and wait for Lock or Condition. Wait for a thread to enter the lock, but wait for other threads to do something

It is important to note that while synchronized and JUC Lock both perform the locking function, threads enter different states. Synchronized blocks a thread, whereas JUC locks/wakes it up with locksupport.park ()/unpark(), which puts the thread into the wait state. On the other hand, although they enter a different state when they are locked, they both enter a runnable state when they are woken up, and the behavior effect is the same. A thread enters the lock, but waits for other threads to perform some action

The main operating

start()

Start a new thread to execute its run() method. A thread can only start once. This is mainly done by calling Native start0().

public synchronized void start() {           // Check whether it is the first startupif(threadStatus ! = 0) throw new IllegalThreadStateException(); group.add(this); boolean started =false; try {               // Start thread start0(); started =true;
        } finally {
            try {
                if(! started) { group.threadStartFailed(this); } } catch (Throwable ignore) { /*do nothing. If start0 threw a Throwable then
                  it will be passed up the call stack */
            }
        }
    }

    private native void start0();
Copy the code

run()

The run() method does not need to be invoked by the user. When a thread is started with the start method, it enters the body of the run method to perform specific tasks when it has acquired CPU execution time. Note that the Thread class must override the run method to define the specific tasks to be performed.

sleep()

There are two overloaded versions of the sleep method

Sleep (long millis,int nanoseconds) // The first argument is millisecond and the second argument is nanosecondCopy the code

Sleep is the equivalent of letting the thread sleep, handing over the CPU, and letting the CPU perform other tasks.

However, it is important to note that the sleep method does not release the lock, which means that if the current thread holds the lock on an object, no other thread can access the object even if the sleep method is called.

yield()

Calling the yield method causes the current thread to surrender CPU permissions, allowing the CPU to execute other threads. It is similar to the sleep method in that it does not release the lock. However, yield does not control the exact time at which the CPU is surrendered. In addition, yield only allows threads with the same priority to obtain CPU execution time.

Note that, unlike the sleep method, invoking yield does not put the thread into a blocked state. Instead, it puts the thread back in a ready state, waiting only for CPU execution time to be retrieved.

join()

There are three overloaded versions of the join method

1 join() 2 Join (long millis) // Parameter is millisecond 3 Join (long millis,int nanoseconds) // First parameter is millisecond, second parameter is nanosecondCopy the code

Join () actually uses wait(), except that it does not wait for notify()/notifyAll() and is not affected by it. It ends if: 1) the waiting time is up; 2) The target thread has run (isAlive()).

public final synchronized void join(long millis) throws InterruptedException {
    long base = System.currentTimeMillis();
    long now = 0;

    if (millis < 0) {
        throw new IllegalArgumentException("timeout value is negative"); } //0 will wait until the target thread has runif (millis == 0) {
        while (isAlive()) {
            wait(0); }}else{// If the target thread has not run out and the blocking time is not up, the calling thread will wait.while (isAlive()) {
            long delay = millis - now;
            if (delay <= 0) {
                break;
            }
            wait(delay); now = System.currentTimeMillis() - base; }}}Copy the code

interrupt()

This will set the thread’s interrupt flag position. What the thread does is up to the thread.

  • If threads such as Sleep (), Wait (), join() are blocked, the thread periodically checks the interrupt status bit and throws InterruptedException at the blocking method calls if the interrupt status bit is true. The thread’s interrupt status bit is cleared immediately after an exception is thrown, i.e., re-new set to false. The exception is thrown to wake up the thread from its blocked state and give the programmer enough time to process the interrupt request before terminating the thread.
  • If a thread is running, contaging for synchronized, lock(), etc., then it is uninterruptible and they ignore it.

Interrupts can be identified in one of three ways:

  • isInterrupted()

    This method only reads the thread’s interrupt flag bit and does not reset it.

  • interrupted()

    This method reads the thread’s interrupt flag bit and resets it.

  • throw InterruptException

    When this exception is thrown, the interrupt flag bit is reset.

At the end

The most important thing is to understand the difference between blocking and waiting. Wait and timeout are easy to understand, meaning that your thread has to wait for a certain amount of time for other threads to operate.

The article is explained by Thread

Daily for praise

Ok, everybody, that’s all for this article, you can see people here, they are real fans.

Creation is not easy, your support and recognition, is the biggest motivation for my creation, we will see in the next article

Six pulse excalibur | article “original” if there are any errors in this blog, please give criticisms, be obliged!