?
Solved

Java Threads - simple example

Posted on 2011-05-01
2
Medium Priority
?
304 Views
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:
A
B
In this case why is the string 'FINISHED!' not printed?

Thanks


public class Test {

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

Expert Comment

by:cmalakar
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.
0
 
LVL 23

Accepted Solution

by:
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:
>>A
>>B
>>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.

0

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