From the course: Parallel and Concurrent Programming with Java 1
Unlock the full course today
Join today to access over 22,600 courses taught by industry experts or purchase this course individually.
Mutual exclusion: Java demo - Java Tutorial
From the course: Parallel and Concurrent Programming with Java 1
Mutual exclusion: Java demo
- [Instructor] To demonstrate how to manually enforce mutual exclusion with locks in Java, I'll modify the example program from earlier with two shoppers that have a data race as the concurrently increment the amount of garlic to buy. First, I'll import the java.util.concurrent.locks package into this program. Then I'll create a new lock object within the shopper class and because Olivia and I used the pencil, I'll give it the creative name of pencil. And I've declared it as a static variable to make it a class variable. In Java, the name, lock, is just an interface for one of several variations of locks. There's not actually a simple lock class, so I'll need to use one of Java's actual concrete classes and, for now, I'll choose to make it a reentrant lock and I'll explain what makes that special in a later video. Now, to keep my two threads from modifying the shared garlic count variable at the same time, I'll call the pencil's lock method at the beginning of the run method before…
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.