JAVA multi-thread wait/notify, multi-thread waitpolicy

Source: Internet
Author: User

JAVA multi-thread wait/notify, multi-thread waitpolicy

This document describes how to use the wait () method and the Y ()/notifyAll () method in JAVA multithreading.

① The wait () and Y/notifyAll methods must be used in the synchronous code block

② Wait () and Y/notifyAll () Execution Process

③ Interrupt the thread that calls the wait () method to enter the waiting queue

④ The notify notification sequence cannot be incorrect.

⑤ Test the change of a condition in multiple threads using if or while?

 

 

① The wait () and Y/notifyAll methods must be used in the synchronous code block

Wait () and policy/policyall () are methods of the Object class. When you execute two methods, you must first obtain the lock. So how to get the lock?

This article describes how to use the Synchronized keyword to obtain a lock. Therefore, wait () and Y/notifyAll () are often used together with synchronized, that is, the wait () and Y/notifyAll () methods are called in the synchronous code block or method modified by synchronized.

 

② Wait () and Y/notifyAll () Execution Process

Because wait () and policy/policyall () are placed in the synchronous code block,Therefore, when threads execute them, they must have entered the critical section, that is, the thread must have obtained the lock.

When the thread executes wait (), it will release the current lock, and then let out the CPU and enter the waiting state.

When executing the notify/notifyAll method, it will wake up a thread waiting for the lock of this object, and then continue to execute until the execution ends and the lock of the object lock (the synchronized code block) then release the lock.

It can be seen from this that the locks are not released immediately after execution of policy/policyall (), but are released after the code in the critical section is executed. Therefore, in actual programming, we should try to exit the critical section immediately after the thread calls y/notifyAll. That is, do not write some time-consuming code after policy/policyall.

Example: (from JAVA multi-thread Core Technology)

 1 public class Service { 2  3     public void testMethod(Object lock) { 4         try { 5             synchronized (lock) { 6                 System.out.println("begin wait() ThreadName=" 7                         + Thread.currentThread().getName()); 8                 lock.wait(); 9                 System.out.println("  end wait() ThreadName="10                         + Thread.currentThread().getName());11             }12         } catch (InterruptedException e) {13             e.printStackTrace();14         }15     }16 17     public void synNotifyMethod(Object lock) {18         try {19             synchronized (lock) {20                 System.out.println("begin notify() ThreadName="21                         + Thread.currentThread().getName() + " time="22                         + System.currentTimeMillis());23                 lock.notify();24                 Thread.sleep(5000);25                 System.out.println("  end notify() ThreadName="26                         + Thread.currentThread().getName() + " time="27                         + System.currentTimeMillis());28             }29         } catch (InterruptedException e) {30             e.printStackTrace();31         }32     }33 }

Call wait () in testMethod () of row 3rd, and call Policy () in synpolicymethod () of row 17th ()

From the code above, we can see that both wait () and notify/notifyAll () can be executed only in the synchronous code block. If the corresponding object lock is not obtained before executing wait () and Y/notifyAll (), a java. lang. IllegalMonitorStateException exception is thrown.

In row 3, when the ThreadA thread executes the lock. wait (); Statement, the obtained object lock is released and the CPU is discarded to enter the waiting queue.

When the other thread executes 23rd rows lock. Y ();, it will wake up ThreadA,But it does not release the lock immediately.Next, it sleeps for 5 seconds (sleep () does not release the lock, in fact, sleep () can also be called in the synchronous code block) until 28th rows, the lock is released only when you exit the critical section modified by synchronized. At this time, ThreadA will have the opportunity to obtain the lock released by another thread and start to execute from the waiting place (Row 3.

 

Next there are two thread classes. The Thread class ThreadA is suspended when calling the testMethod () method to execute lock. wait (); and the other Thread class synpolicymethodthread calls synpolicymethod () to wake up the suspended thread. The Code is as follows:

 

 1 public class ThreadA extends Thread { 2     private Object lock; 3  4     public ThreadA(Object lock) { 5         super(); 6         this.lock = lock; 7     } 8  9     @Override10     public void run() {11         Service service = new Service();12         service.testMethod(lock);13     }14 }15 16 public class synNotifyMethodThread extends Thread {17     private Object lock;18 19     public synNotifyMethodThread(Object lock) {20         super();21         this.lock = lock;22     }23 24     @Override25     public void run() {26         Service service = new Service();27         service.synNotifyMethod(lock);28     }29 }

 

 

Next is the test class:

 1 public class Test { 2  3     public static void main(String[] args) throws InterruptedException { 4  5         Object lock = new Object(); 6  7         ThreadA a = new ThreadA(lock); 8         a.start(); 9 10         NotifyThread notifyThread = new NotifyThread(lock);11         notifyThread.start();12 13         synNotifyMethodThread c = new synNotifyMethodThread(lock);14         c.start();15     }16 }

 

③ Interrupt the thread that calls the wait () method to enter the waiting queue

The sample code is as follows:

1 public class Service {2 3 public void testMethod (Object lock) {4 try {5 synchronized (lock) {6 System. out. println ("begin wait ()"); 7 lock. wait (); 8 System. out. println ("end wait ()"); 9} 10} catch (InterruptedException e) {11 e. printStackTrace (); 12 System. out. println ("exception"); 13} 14} 15} 16 17 public class ThreadA extends Thread {18 19 private Object lock; 20 21 public ThreadA (Object lock) {22 super (); 23 this. lock = lock; 24} 25 26 @ Override27 public void run () {28 Service service = new Service (); 29 service. testMethod (lock); 30} 31}

Note that the 23rd-line wait () method is called by the Object lock of the Object class. The following interrupt () method is called by ThreadA class objects. In ThreadA, the Object is passed to the testMethod () method as a parameter, and the run () method of ThreadA calls testMethod () to wait () pause the thread of ThreadA (pause the thread currently executing wait ). Here we can see a difference:

Thread-related methods in the Object class:

1) Policy/policyall

2) wait ()/wait (long)

Related methods in java. lang. Thread:

1) interrupt ()

2) sleep ()/sleep (long)

3) join ()/suspend ()/resume ()....

The test code is as follows:

 1 public class Test { 2  3     public static void main(String[] args) { 4  5         try { 6             Object lock = new Object(); 7  8             ThreadA a = new ThreadA(lock); 9             a.start();10 11             Thread.sleep(5000);12 13             a.interrupt();14         } catch (InterruptedException e) {15             e.printStackTrace();16         }17     }18 }

When you execute the interrupt () of line 1, the thread in the wait is "immediately" awakened (usually immediately responds to the interrupt request) and throws an exception. The thread ends.

 

④ The notify notification sequence cannot be incorrect.

Assume that wait () is executed in thread A and Y () is executed in thread B (). However, if thread B executes thread y () and then ends, thread A executes wait (), then thread A cannot beNormalWake up (you can also wake up by throwing an exception through the interrupt () method mentioned in ③ ^ ~ ^ ).

In this article, the third point in the communication mode between threads in JAVA multithreading mentions that an error in the notify notification sequence will cause the thread that calls wait () to enter the waiting queue to no longer wake up.

 

⑤ Test the change of a condition in multiple threads using if or while?

I have never understood why while is used instead of if ??? Until I see this simple example, I finally understand ....

This example is as follows:

There are two threads that delete data from the List, and only one thread adds data to the List. Initially, the List is empty. Data in the List can be deleted only after data is added to the List. After the data adding thread adds data to the List, it calls yyall () to wake up two deletion threads, but it only adds one data. Now there are two wake-up deletion threads, what should I do ??

If you use if to test the number of data in the List, IndexOutofBoundException will appear., Out-of-bounds exception. The reason is that there is only one data in the List. After the first deletion thread deletes the data and the second thread executes the deletion operation again, the deletion fails and IndexOutofBoundException is thrown.

However, if you use the while command to test the number of data in the List, no exception occurs.!!! Magic.

When the conditions for wait change, the logic of the program may be disordered.--- That is, there is no data in the List, and there are threads to delete the data. Therefore, we need to use the while loop to determine the condition change, rather than the if statement.

Example: from JAVA multi-thread programming Core Technology

Add class, responsible for adding data:

public class Add {    private String lock;    public Add(String lock) {        super();        this.lock = lock;    }    public void add() {        synchronized (lock) {            ValueObject.list.add("anyString");            lock.notifyAll();        }    }}

public class ThreadAdd extends Thread {

    private Add p;

    public ThreadAdd(Add p) {
        super();
        this.p = p;
    }

    @Override
    public void run() {
        p.add();
    }
}

 

Subtract class, responsible for deleting data ----First, you must determine the conditions and then execute wait (). This means that the conditions for wait may change !!!

Public class Subtract {private String lock; public Subtract (String lock) {super (); this. lock = lock;} public void subtract () {try {synchronized (lock) {if (ValueObject. list. size () = 0) {// change the if value here to while to ensure that there is no cross-border Exception !!!! System. out. println ("wait begin ThreadName =" + Thread. currentThread (). getName (); lock. wait (); System. out. println ("wait end ThreadName =" + Thread. currentThread (). getName ();} ValueObject. list. remove (0); System. out. println ("list size =" + ValueObject. list. size () ;}} catch (InterruptedException e) {e. printStackTrace ();}}}

Public class ThreadSubtract extends Thread {

Private Subtract r;

Public ThreadSubtract (Subtract r ){
Super ();
This. r = r;
}

@ Override
Public void run (){
R. subtract ();
}
}

 

Encapsulated List queue:

public class ValueObject {    public static List list = new ArrayList();}

 

Test class:

public class Run {    public static void main(String[] args) throws InterruptedException {        String lock = new String("");        Add add = new Add(lock);        Subtract subtract = new Subtract(lock);        ThreadSubtract subtract1Thread = new ThreadSubtract(subtract);        subtract1Thread.setName("subtract1Thread");        subtract1Thread.start();        ThreadSubtract subtract2Thread = new ThreadSubtract(subtract);        subtract2Thread.setName("subtract2Thread");        subtract2Thread.start();        Thread.sleep(1000);        ThreadAdd addThread = new ThreadAdd(add);        addThread.setName("addThread");        addThread.start();    }}

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.