Win a copy of Design for the Mind this week in the Design forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Thread(why so ?)

 
Shubhada Nandarshi
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi friends;

see following code



public class Test extends Thread{
public String g="";
public static void main(String argv[]){
Test r = new Test("one");
Test a=new Test("two");
Thread t = new Thread(r);

Thread t1 = new Thread(a);
t.start();
t1.start();
}

Test(String s){
g=s;
}
public synchronized void run(){
for(int i=0;i<2;i++){

try{
sleep(1000);
}
catch(InterruptedException e){}

System.out.println(g);
}

}

}




I am getting following as o/ps at different time, for above code.
1>two
one
two
one

2>one
two
one
two


why so? the code is compiling perfectly.
Thread of 'one' is starting 1st then how this o/p is getting
executed ?s it bcoz both start() methods are together???(one below the other)
but this can't be the ans?

Please can any one help me?


Thanks.

Shubha.
 
Rachana Sharma
Greenhorn
Posts: 15
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
hi shubha,
i understand the reason for the inconsistent output is that when we call the start method on a thread is actually placed in a runnable state where it is eligible to be choosen by the scheduler for running(the actual state where the thread is alive).
so, there is no garuntee that if a thread calls its start method first it will be executed then and there, it all depends on the scheduler.
hope this helps to understand the reason for different outputs when the same code is run many times.
 
Abdulla Mamuwala
Ranch Hand
Posts: 225
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Shobha, keeping in mind what Rachana said why don't you try interchanging the call of start() method's on your thread objects, i.e., why dont you try something like this,



You will observe that it will show up inconsistent results most of the times, the thread scheduler is to blame for that.
 
Shubhada Nandarshi
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
But is there any method or way which will take the thread for execution in order of their creation?

How to overcome this problem??
(This may be not for SCJP, but I want to get know.)

Shubha.
 
vidya sagar
Ranch Hand
Posts: 580
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hi


But is there any method or way which will take the thread for execution in order of their creation?


Use join method

t.start();(after this line)
t.join()--------->add this
t1.start();
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic