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?