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("Proces ses completed:" + other.processCount);
} catch (InterruptedException ex) {}
}
System.out.println("FINISH ED!");
}
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");
}
}
}
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("Proces
} catch (InterruptedException ex) {}
}
System.out.println("FINISH
}
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");
}
}
}
ASKER CERTIFIED SOLUTION
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
As the main function and Server runs in different threads and they both synchronize on the same object the program behaves differently.