Reputation: 1582
I have written a simple java program and I was hoping for an output like
go
hello
bye //pause for 2 seconds
hello
But it is giving an output like
go
bye
hello //pause for 2 sec
hello
Programme:
class Tread{
public static void main(String[] args){
Hello h= new Hello();
Thread t= new Thread(h);
System.out.println("go");
t.start();
System.out.println("Bye");
}
}
class Hello implements Runnable{
public void run(){
System.out.println("hello");
try{
Thread.sleep(2000);
}
catch(Exception e){ }
System.out.println("hello");
}
}
Please, can anybody tell me why i am not getting the desired otput?
Upvotes: 0
Views: 69
Reputation: 39
I guess because it is on another thread, independent from main program. Try this:
public static void main(String[] args){
Hello h= new Hello();
Thread t= new Thread(h);
System.out.println("go");
t.start();
try {
Thread.sleep(1000);
}
catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
System.out.println("Bye");
}
}
class Hello implements Runnable{
public void run(){
System.out.println("hello");
try{
Thread.sleep(2000);
}
catch(Exception e){}
System.out.println("hello");
}
}
Upvotes: 0
Reputation: 4819
The result is unpredictable since 2 threads try to write something on the output simultaneously. The JVM specs do not specify the order of the operations:
So, all of this is implementation dependant: somebody may use another JVM, one day, and/or another operating system, and he could then have another behaviour. With your JVM, on your environment, you may encounter millions of run of this program writing output in the same order. But it does not mean that it will never change in the future.
If you want the sequence of operations to be done according to a particular order, you need to use some locks, or synchronized
keyword to access resources.
Thinking it will always behave the same often leads to mistakes, that happen only occasionally, and that we call race conditions.
Upvotes: 1