From the course: Complete Guide to Parallel and Concurrent Programming with Java
Unlock this course with a free trial
Join today to access over 24,700 courses taught by industry experts.
Race condition: Java demo - Java Tutorial
From the course: Complete Guide to Parallel and Concurrent Programming with Java
Race condition: Java demo
- [Instructor] This example demonstrates a race condition in Java. It has a class named shopper, which will execute as a thread that either adds or multiplies the value of the bags of chips class variable on line nine, which represents the number of chips we should buy for the party. Down in the program's main method, I use a four loop on line 41 to instantiate 10 shoppers. Five of those threads are named Barron with a unique number afterwards, and the other five are named Olivia. As in our kitchen scenario, the five Olivia threads will each add three bags of chips to the shared variable, whereas the five Barron threads will each double the amount of chips. That's accomplished in the shopper classes run method by using an if else statement beginning on line 17 that checks the name of the thread. Notice that in either case, the shopper is locking and unlocking a reentrant lock named pencil, which serves as the shared mutex to protect access to the shared bags of chips variable. Since…
Practice while you learn with exercise files
Download the files the instructor uses to teach the course. Follow along and learn by watching, listening and practicing.