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.

Try lock: Java demo

Try lock: Java demo - Java Tutorial

From the course: Parallel and Concurrent Programming with Java 1

Start my 1-month free trial

Try lock: Java demo

- [Instructor] To demonstrate the try lock method in Java, I've created this example that simulates two shoppers searching for the items they need and then adding to a shared notepad. In this shopper class, each shopper has their own instance variable on line nine for the number of items they need to add to the notepad, which is how many items they found in a coupon book or perhaps missing from the fridge. The static integer on line 10 represents the number of items they've added to the shared notepad, and the pencil on line 11 is the lock that's used to protect access to it. Down in the run method, the while loop on line 18 will keep the shoppers searching for items and adding them to the shared notepad until there are at least 20 items. If the shopper has items to add to the notepad, they'll execute the if clause on line 19, in which they lock the pencil, add all of their items to the list, and then print a message with how many items they added. That then resets their items to add…

Contents