Java Threads - simple example

Posted on 2011-05-01
Medium Priority
Last Modified: 2012-06-27
Why does the following code display 'Processes completed: 500000' or 'Processes completed: 499999' instead of 'Processes completed: 0'  ?

And very occasionally the output is just:
In this case why is the string 'FINISHED!' not printed?


public class Test {

      public static void main(String[] args)  {
            Server other = new Server();
            synchronized(other) {
                  try {
                        System.out.println("Processes completed:" + other.processCount);
                  } catch (InterruptedException ex) {}
       static class Server extends Thread {
                  int processCount;
                  public void run() {
                        synchronized(this) {
                              for (int i=0;i<500000;i++) {
                                    processCount = i;
                        processCount += 1;
Question by:robocop100
  • 2
LVL 23

Expert Comment

ID: 35500378
All because of "synchronized" statements.

As the main function and Server runs in different threads and they both synchronize on the same object the program behaves differently.
LVL 23

Accepted Solution

cmalakar earned 500 total points
ID: 35500407
>> Why does the following code display 'Processes completed: 500000' or 'Processes completed: 499999' instead of 'Processes completed: 0'  ?

case A:
When main thread enters the synchronized block first, and Server thread enters the synchronized block next.
   1) main thread waits for the lock, and goes to waiting state.
   2) Server threads notifies main thread. But main thread will start execution only when server thread releases the lock on synchronized block. Server thread releases the lock only when whole for loop completes.
       When the for loop is completed, the value of processCount is 499999. If the main thread gets its turn to execute immediately after Server thread completes execution, it prints 499999. Otherwise it prints 500000.

>>And very occasionally the output is just:
>>In this case why is the string 'FINISHED!' not printed?

Case B:
When the Server thread enters the synchronized block first.
    1) Main thread will enter the synchronized block only when the Server thread comes out of for loop.
    2) And if the main thread waits on the lock, no one notifies as the Server thread is out of for loop,
main thread waits forever, and you don't see FINISHED output.


Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers will learn about basic arrays, how to declare them, and how to use them. Introduction and definition: Declare an array and cover the syntax of declaring them: Initialize every index in the created array: Example/Features of a basic arr…
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…
Suggested Courses
Course of the Month14 days, 13 hours left to enroll

840 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question