Threads in Java

We need to control access to shared state ( when multiple threads are at work ), to avoid unexpected results.

In the case of the program below the shared state is the int sheepCount.

10 different threads call the method incrementAndReport() .

Without thread management 

Output ( wonky )

Every thread is trying to get access to the method incrementAndReport() , and its all over the place


With Thread access management

Each time the method is called by a Thread, its completed by that Thread (other threads locked out until finished)


This is done with the help of the keyword synchronized


important ( see DONT DO THIS )

Don’t use a local method variable to synchronize on :

as it will be a new variable for every thread and the lock won’t work



Some notes for Oracle cert (OCPJP 11 ), I’ve currently studying for (last time I did a Java cert Sun Microsystems was the vendor yikes !).

This is based on a program in the Jeanne Boyarsky / Scott Selikoff book

2 thoughts on “Threads in Java”

Leave a Comment