From the course: Parallel and Concurrent Programming with Java 1

Unlock the full course today

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

Data race: Java demo

Data race: Java demo - Java Tutorial

From the course: Parallel and Concurrent Programming with Java 1

Start my 1-month free trial

Data race: Java demo

- [Instructor] To demonstrate a data race in Java, I've created this simple program that uses two threads to concurrently increment a shared counter variable. The Shopper class on line five extends Thread and will be used to represent one of two shoppers. Olivia or me. The static class variable on line seven is a counter for the amount of garlic we should buy and it gets initialized to zero. Within the thread's run method on line nine, I simply use a for loop to increment that garlicCount variable ten times. Down in the program's main method on lines 17 through 22, I create two shopper threads called barron and olivia; start them both and then used the join method to wait until they're both done. Finally, I print out the value of the garlicCount class variable on line 23, indicating how much garlic we should buy. When I run this program, it tells me that we should buy 20 garlic. And that makes sense. I have two threads here that are each adding 10 garlic to the counter. And if I run…

Contents