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.

Synchronized statement: Java demo

Synchronized statement: Java demo - Java Tutorial

From the course: Parallel and Concurrent Programming with Java 1

Start my 1-month free trial

Synchronized statement: Java demo

- [Instructor] Rather than marking an entire method as synchronized, Java also makes it possible to synchronize sections of code with a synchronized statement. When creating an synchronized statement, you specify the object that will provide the intrinsic lock. Before a thread can execute the code contained within the synchronized statement, it must first acquire the intrinsic lock associated with the specified object and then when the thread is done, it will release its hold on that lock. To demonstrate creating a synchronized statement, I'll modify the data race example program that I have been using for the past few videos which has two concurrent threads incrementing a shared counter variable 10 million times each. I want to synchronize access to line 11 which increments the shared garlicCount variable. So I'll wrap that line in a synchronized statement and I'll give it the shopper.class object to use for the intrinsic lock. When I run this program both threads will be acquiring…

Contents