当前位置:网站首页>[multithreading] thread communication scheduling, waiting set wait(), notify()

[multithreading] thread communication scheduling, waiting set wait(), notify()

2022-06-27 16:39:00 51CTO

Catalog


Object waiting set to interfere with thread scheduling

wait and notify In order to deal with the randomness of thread scheduling .

Or that sentence , Multithreaded scheduling , Because of its randomness , It leads to the code who executes first , Who's going to do it later , There are too many variables .

And we programmers don't like randomness , We like certain things .

Need to be able to get threads to each other , There is a fixed order .

for instance : To play basketball
There is a typical operation in basketball : Pass the ball , Layup .
Then we must pass the ball first , Lay up again . It requires the cooperation of two team members .
Two players are two threads .
If it's a layup first , But the ball didn't reach , Also on a lonely .
Generally, the most stable method , They pass the ball first and then lay up .

In this order , It is also very necessary in our actual development .
Therefore, we need to have means to control !

As mentioned before join It is also a way of sequential control , however join Prefer to control the end of the thread . therefore join There are limitations in use .

It's not like wait and notify More suitable for use .


wait Method

Actually wait() The method is to stop the thread .

  1. Method wait() Its function is to make the current thread executing code wait ,wait( ) The method is Object Class method , This method is used to put the current thread into “ Pre execution queue ” in , And in wait() Stop execution at code , Until notified or interrupted .
  2. wait( ) Method can only be invoked in synchronous or synchronous blocks. . If the wait() when , Not holding the proper lock , It throws an exception .
  3. wait( ) After method execution , The current thread releases the lock , And has been waiting for notification , Until other threads wake up the thread and compete with other threads to re acquire the lock .

【 Multithreading 】 Thread communication scheduling 、 Waiting set wait() 、notify()_ Thread scheduling

【 Multithreading 】 Thread communication scheduling 、 Waiting set wait() 、notify()_ Multithreading _02

call wait Method thread , It's going to get stuck , Blocked until another thread passes notify To inform .

public class ThreadTest2 {
    public static void main(String[] args) {
        Object locker = new Object();
        Thread t = new Thread() {
            @Override
            public void run() {
                synchronized (locker) {
                    System.out.println("t  Began to run ");
                    try {
                        locker.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(" t  End of run ");
                }
            }
        };
        t.start();
    }
}

     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.

【 Multithreading 】 Thread communication scheduling 、 Waiting set wait() 、notify()_Java_03


notify Method

A thread executes to object.wait() Then I waited , Then the program can't wait like this . At this time, you need to use another method to wake up notify().

notify The method is to make the stopped thread continue to run

  1. Method notify() It is also invoked in synchronous or synchronous blocks , This method is used to notify other threads that may be waiting for the object lock of the object , Give notice to notify, And make them regain the object lock of the object . If there are multiple threads waiting , Then a thread planner randomly selects one wait Thread in state .
  2. stay notify() After the method , The current thread will not release the object lock immediately , Wait until the execution notify() Method to finish executing the program , That is, the object lock will not be released until the synchronization code block is exited .
public class Test18 {
    //  In order that the two threads can interact smoothly , We create a lock object 
    private static Object locker = new Object();

    public static void main(String[] args) throws InterruptedException {
        Thread t1 = new Thread(()->{
            // Conduct  wait
            synchronized (locker){
                System.out.println("wait  Before ");
                try {
                    locker.wait();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                System.out.println("wait  after ");
            }
        });
        t1.start();

        //  In order that we can observe the phenomenon more clearly , I'm going to use  sleep  Delay 3s
        Thread.sleep(3000);

        Thread t2 = new Thread(()->{
            //  Conduct  notify
            synchronized (locker){
                System.out.println("notify  Before ");
                locker.notify();
                System.out.println("notify  after ");
            }
        });
        t2.start();
    }
}

     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.

【 Multithreading 】 Thread communication scheduling 、 Waiting set wait() 、notify()_ Thread communication _04

According to this mechanism, we can arrange the sequence of multiple threads

【 Multithreading 】 Thread communication scheduling 、 Waiting set wait() 、notify()_ Thread scheduling _05


notifyAll Method

As mentioned above wait and notify All operate on the same object .

for example :

Now there is An object o, By 10 A thread called o.wait.
here 10 individual Threads are blocked .
If called o.notify, It will 10 One of the threads wakes up

【 Random wake up : Not sure which thread will be awakened next 】

The awakened thread will continue to execute . Other threads are still blocked .

If Called o.notifyAll, will Wake up all threads
wait After being awakened , Will try again to get the lock , There will be competition in this process

Wake up all threads , Grab the lock .

I got it , Then we can carry on .
Failed threads , Continue to wait for , Waiting for the next notifyAll.**


wait Methods to summarize

  • wait( ) The role of is Put the current thread into a waiting state , meanwhile ,wait( ) It also causes the current thread to release the lock it holds .

Until another thread calls the notify() Method or notifyAll() Method , Wake up the current thread ( Get into “ Ready state ”)

  • notify() and notifyAll() The role of , Wake up the waiting thread on the current object

notify() Is to wake up a single thread

notifyAll() Is to wake up all threads , Then these threads compete for the same lock .( Not recommended notifyAll )

  • wait(long timeout) Leave the current thread in “ wait for ( Blocking ) state
  1. “ until Other threads call the... Of this object notify() Method or notifyAll() Method

  2. perhaps Over a specified amount of time ”, The current thread is awakened ( Get into “ Ready state ”)

summary :

wait() The working process of is :

  1. Release object lock ( So there must be a lock to execute normally )
  2. Wait for a notice ( It may take a long time , Because they don't participate in the competition of subsequent locks Until another thread calls the object's notify() To wake up the thread )
  3. After receiving the notice Try to reacquire the object lock So let's keep going

Particular attention

  1. wait() and notify() The operation must be placed in synchronized Within the code block of Otherwise, an exception will be reported

  2. call wait() and notify() The object of must be the same object To wait and wake up

    More precisely : because wait and notify To be in synchronized Within the code block So the locked object should also be the same as wait() and notify() The object of must be the same object This is the 4 Objects must be consistent


notify Methods to summarize

  • A thread executes to object.wait() Then I waited , Then the program can't wait like this . At this time, you need to use another method to wake up notify().
  • notify The method is to make the stopped thread continue to run .
  1. Method notify() It is also invoked in synchronous or synchronous blocks , This method is used to notify other threads that may be waiting for the object lock of the object , Give notice to notify, And make them regain the object lock of the object . If there are multiple threads waiting , Then a thread planner randomly selects one wait Thread in state .
  2. stay notify() After the method , The current thread will not release the object lock immediately , Wait until the execution notify() Method to finish executing the program , That is, the object lock will not be released until the synchronization code block is exited .

Be careful :

Wake up the thread not too early , If there is no thread waiting , Premature wakeup of threads , At this time, there will be wake-up first , Waiting for the effect .

such There is no need to run wait The method . Leading to race condition problems

public class ThreadTest3 {
    public static void main(String[] args) {
        Object locker = new Object();
        Thread t = new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep(2000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                synchronized (locker) {
                    System.out.println(" t  Began to run ");
                    try {
                        locker.wait();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    System.out.println(" t  End of run ");
                }
            }
        };
        t.start();

        Thread t1 = new Thread() {
            @Override
            public void run() {
                synchronized (locker) {
                    System.out.println(" t1  Began to run ");
                    locker.notify();
                    System.out.println(" t1  End of run ");
                }
            }
        };
        t1.start();

        Thread t2 = new Thread() {
            @Override
            public void run() {
                synchronized (locker) {
                    System.out.println(" t2  Began to run ");
                    System.out.println(" t2  End of run ");
                }
            }
        };
        t2.start();
    }
}



     
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 10.
  • 11.
  • 12.
  • 13.
  • 14.
  • 15.
  • 16.
  • 17.
  • 18.
  • 19.
  • 20.
  • 21.
  • 22.
  • 23.
  • 24.
  • 25.
  • 26.
  • 27.
  • 28.
  • 29.
  • 30.
  • 31.
  • 32.
  • 33.
  • 34.
  • 35.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.

Running results :

【 Multithreading 】 Thread communication scheduling 、 Waiting set wait() 、notify()_ Thread wait set _06


Race condition problem

  • Race condition problem When one t The thread executes wait() Method releases the object lock Another one t1 The thread acquires the lock and immediately executes notify() Method area notification t Threads however t The thread has not yet executed the code waiting for notification So the notice was missed This thread t It's going to wait This is a race condition problem
  • In order to solve and Avoid this problem In fact, when we are executing wait() During operation Releasing the lock and waiting for the notification to be received are performed in an atomic nature Finally, try to re acquire the lock

wait And sleep Comparison of

  1. wait For communication between threads sleep Used to block threads for a period of time
  2. wait There must be a lock before wait Then the lock will be released Try to request the lock again after being awakened
  3. sleep It ignores the existence of locks I.e. no lock is required And will not release the lock
  4. wait yes object Methods
  5. sleep yes thread Static method of
  6. The only thing in common is that you can let the thread give up execution for a period of time

原网站

版权声明
本文为[51CTO]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/178/202206271523395328.html

随机推荐