Wait, Notify, Sleep, Join and Thread Synchronization

xiaoxiao2021-03-06  53

Wait, Notify, Sleep, Join These methods are commonly used, which involves multi-threaded and synchronous problems, here is slightly explained.

1.Wait and Notify These methods are the ways in object, because they are very close. Wait is waiting for the synchronous lock of this object, but call this method must first get the synchronization lock of this object first, A lot of people are dizzy. Here first explains these two methods and gives a small example of explanation.

WAIT: Synchronous lock waiting for the object, you need to get the synchronization lock of the object to call this method, otherwise you receive an IllegalMonitorstateException, this is an exception. After calling this method, give up this synchronous lock. If you don't bring The WAIT method of the parameter is only waiting for others to wake up. If you take a parameter, you will wait longer. After this time, even if no one wakes up this thread, it is no longer waiting.

Notify: Wake Waken Threads Waiting for the Object Synchronous Lock (I only wake up one, if there is a waiting), but NotifyAll can wake all the wait threads, pay attention to the wake-up at the Wait thread before Notify, there is no effect.

Here, there is a popular example, two people have a bathroom (only one person can be used each time), they all have to brush their teeth and convenient, they are trying, the first person is first brushing, then the second person brush teeth ...

Class syn {public static void main (string [] args) throws exception {twovernness (); twovern.tart (); twovern.tart ();

Class twoteople extends thread {private int i = 0; static thread one = new twovern (1); static thread two = new twovern (2);

Static Object Washroom = New Object (); Private TWOPEOPLE (INT i) {this.i = i;} public void Run () {synchronized (Washroom) {try {if (i == 1) {brush (); // 1 Washroom.wait (); // 2 release (); //6 Washroom.Notify (); //7} else {brush (); // 3 Washroom.Notify (); // 4 Washroom.wait () ; //5 Release (); // 8}} catch (interruptedException e) {E.PrintStackTrace ();}}} private void brush ()}} private void brush ()} i "is brushing!" ); Try {thread.sleep (2000);} catch (interruptedException e) {E.PrintStackTrace ();} // delay two seconds to see effect system.out.println ("people i " HAS BURSHED! "); } Private void release () {system.out.println ("people" i "is release!"); Try {thread.sleep (2000);} catch (Interrupted) Exception E) {E.PrintStackTrace ();} // Delayed two seconds to see effect system.out.println ("people" i "HAS RELEASED!");}}; The above code is short, but also shows the execution order As for Join and SLEEP or discussed next time.

转载请注明原文地址:https://www.9cbs.com/read-93604.html

New Post(0)