Home arrow static arrow Java Programming [Archive] - Help required
Warning: Creating default object from empty value in /www/htdocs/w008deb8/wiki/components/com_staticxt/staticxt.php on line 51
Java Programming [Archive] - Help required
This topic has 3 replies on 1 page.

Posts:28
Registered: 7/2/04
Help required  
Jul 2, 2004 3:56 AM



 
Hello all,

Can anyone explain the flow of this program which uses thread ...

import java.lang.*;
public class Greeting extends Thread {
public Greeting () {
System.out.println("kiran");
}
public void run() {
for (int i=0;i<2;i++){
printMsg();
}
}
public void printMsg() {
Thread tt = Thread.currentThread();
String name=tt.getName();
System.out.println("name =" + name );
}

public static void main(String args[]) {
Greeting t= new Greeting();
System.out.println("thread is alive =" +t.isAlive() +t.getName());
t.start();
System.out.println("thread is alive =" +t.isAlive() +t.getName());
for(int i=0;i<2;i++){
t.printMsg();
}
}
}

And the output of this program is .....
kiran
thread is alive =falseThread-0
thread is alive =trueThread-0
name =main
name =main
name =Thread-0
name =Thread-0
 

Posts:833
Registered: 1/2/04
Re: Help required  
Jul 2, 2004 4:02 AM (reply 1 of 3)



 
The above program creates one single thread which runs twice and calls printMsg().
ANd PrintMsg() displays the name of the thread.
 

Posts:28
Registered: 7/2/04
Re: Help required  
Jul 2, 2004 5:43 AM (reply 2 of 3)



 
I understand that but I would like to know when once the thread is started by t.start(),which in turn shud call the run() method and shud rather execute it...why does the control go to the second printout statement in main().Can you explain it in detail...
What is the difference between the name of the thread as (main and Thread-0 ,as given in the output ),from where does it get these names.
 

Posts:7,499
Registered: 02-11-14
Re: Help required  
Jul 2, 2004 6:02 AM (reply 3 of 3)



 
The name of the Thread is generated behind the scenes during thread creation...

To understand more about the complex nature of when a thread gets called, look at [url=http://java.sun.com/docs/books/tutorial/essential/threads/]This Tutorial[/url], specifically, look at the Life Cycle and Thread Priority sections.

The general nature of the threads is that, even though you call start() (from the main thread), and the thread begins, it will not necessarily be run before the next lines of code after start() is called. Java will try to run the Threads simultaneously, but that is impossible on computers with one CPU, and when the same resource is being used (ie System.out). So java has to determine which one to execute. It does so based on priority, but there is no gaurantee as to what order the threads will be executed in... thus the need for synchronization and such...
 
This topic has 3 replies on 1 page.