Link to home
Start Free TrialLog in
Avatar of robocop100
robocop100

asked on

Java Threads - simple example

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");
                  }
            }
}
Avatar of cmalakar
cmalakar
Flag of India image

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.
ASKER CERTIFIED SOLUTION
Avatar of cmalakar
cmalakar
Flag of India image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial