Test the change of a condition in multi-threading with if or while?

Source: Internet
Author: User

I've never been able to understand when a condition needs to be tested in the run () method of a thread, why use while instead of if, until you see this simple example, finally understand ....

The example is this:

There are two threads that delete data from the list, and only one thread adds data to the list. Initially, the list is empty and the data in the list can be deleted only after the data has been added to the list. When the thread that added the data added data to the list, called Notifyall (), woke up two delete threads, but it only added one data and now has two wake-up delete threads, what do I do??

If you test the number of data in the list with the IF, you will get a indexoutofboundexception, out-of-bounds exception. The reason is that the list has only one data, the first delete thread after the data is deleted, the second thread to perform the delete operation, the deletion fails, thereby throwing indexoutofboundexception.

However, if you use while to test the number of data in the list, there will be no cross-border exceptions!!! Magic.

When the wait condition changes, the logic of the program is confusing---that there is no data in the list, and then the thread goes to perform the operation of deleting the data. Therefore, it is necessary to use the while loop to determine the condition change, rather than using the IF.

Test the change of a condition in multi-threading with if or while?

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.