Luther Luther - 2 months ago 13
Java Question

Java, Threads, will only run() block be part of the thread or also the code after a start() call?

I'm starting Threads in java, I would like to have a clear idea of how

start()
/
run()
acts in my situation.

I've created a thread calle t, and I've placed
t.start()
followed by a for cycle.

Will the for cycle be part of the thread.t or is it part of the main thread??




class Job implements Runnable{
Thread t;

Job(String tName){
t=new Thread(this, tName);
System.out.println("This is thread: "+t.getName());
t.start();
System.out.println("This is the end of constructor");
try{ /*<<<<<<<------------WILL THIS RUN in my MAIN thread or in the t thread??*/
for(int i=0;i<5;i++){
System.out.println("xxxThis is the count i value: "+i+" "+ t.getName());
Thread.sleep(1000);
}
}
catch(InterruptedException e){
System.out.println("The thread has been interrupted");
}

}

public void run(){
System.out.println("This is the start of RUN()");
try{
for(int i=0;i<5;i++){
System.out.println("This is the count i value: "+i+" "+ t.getName());
Thread.sleep(1000);
}
}
catch(InterruptedException e){
System.out.println("The thread has been interrupted");
}
finally{
System.out.println("Fnally block reached: "+t.getName());
}
}
}

Answer

I would like to have a clear idea of how start()/run() acts in my situation

start() method spawns a new thread of execution and executes the run method in that thread. In this case , the thread will have its own call stack. Whereas, calling run() method directly doesn't spawns a new thread. Instead this will cause the run() method to execute in the current executing thread having old call stack.

Will the for cycle be part of the thread.t or is it part of the main thread??

The for cycle will be part of the Thread(in your case is main thread if you create Job instance in main thread) from which Thread t is spawned. And if you want to confirm then simply print the name of thread which is executing that for loop using Thread.currentThread().getName() . Example:

try{   /*<<<<<<<------------WILL THIS RUN in my MAIN thread or in the t thread??*/
    System.out.println(Thread.currentThread().getName()+" is executing this for loop");
    for(int i=0;i<5;i++){
        System.out.println("xxxThis is the count i value: "+i+" "+ t.getName());
        Thread.sleep(1000);
    }
Comments