JP Morgan Interview Question
Java DevelopersTeam: 100
Country: India
Interview Type: In-Person
RUN is like common Method .
IF you call run MEthod Twice
run() isn't a special method. It works just like any other method you declare. If you call it, the main thread (actually, the thread you call it from) will run the code in the run method.
If you call run() twice, you simply execute the code twice. Not parallel, but sequentially.
Thread's start() has a completely different purpose. start() gets a new OS thread and lets it execute the code in the Thread's (overridden) run() method, or if you construct a Thread with a Runnable as the argument, it will let the thread execute the code in that Runnable's run() method.
A Thread models a single thread over time. When it's done running code, it's done. You can't start it again.
start() method creates a thread and registers it with a thread scheduler, where thread scheduler deals with prioritization and other thread related functionalities and then calls a run() method. So run() method is simply like any other java method which doesn't have any thread nature until and unless it is called through start() method
run the following program and see output :) It prints out current thread name as main when you call t1.run(); and t2.run() explicitely in main
package threadpool;
public class ExtendThread extends Thread {
public void run(){
System.out.println("Thread running = " + Thread.currentThread().getName());
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
Thread t1 = new ExtendThread();
Thread t2 = new ExtendThread();
t1.start();
t2.start();
t1.run();
t2.run();
}
}
In Java you can create a thread in two different ways:
1. Inherit from Thread. - to start this thread one calls start()
2. Implement the Runnable interface - to start this thread one calls run()
-->start() method starts a completely new thread and calls run() method to execute it, hence obeys the basic law of threading.
- Aman Raj March 16, 2014--> In case of run() method, no new thread it created and method executes on current thread as all other methods do.