aspose file tools*
The moose likes Programmer Certification (SCJP/OCPJP) and the fly likes Thread(why so ?) Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Certification » Programmer Certification (SCJP/OCPJP)
Bookmark "Thread(why so ?)" Watch "Thread(why so ?)" New topic
Author

Thread(why so ?)

Shubhada Nandarshi
Ranch Hand

Joined: Jun 10, 2005
Posts: 59
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.


Shubhada
Rachana Sharma
Greenhorn

Joined: Jun 21, 2005
Posts: 15
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

Joined: Jan 09, 2004
Posts: 225
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

Joined: Jun 10, 2005
Posts: 59
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

Joined: Mar 02, 2005
Posts: 580
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();
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Thread(why so ?)
 
Similar Threads
Threads & synchronization
Regarding Threads
holdsLock is working strange
Thread Question about sleep method
doubt in threads