From the course: Parallel and Concurrent Programming with Java 2

Unlock the full course today

Join today to access over 22,400 courses taught by industry experts or purchase this course individually.

Race condition: Java demo

Race condition: Java demo - Java Tutorial

From the course: Parallel and Concurrent Programming with Java 2

Start my 1-month free trial

Race condition: Java demo

- [Narrator] 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 for loop on line 41, to instantiate 10 shoppers. Five of those threads are named Barron, with a unique number afterwords, 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 reinterent lock named pencil, which serves as the shared new text to protect access to the shared bags of chips…

Contents