It may be a basic question, i was confused with this,
in one file i have like this :
public class MyThread extends Thread {
#Override
public void run() {
//stuffs
}
}
now in another file i have this :
public class Test {
public static void main(String[] args) {
Thread obj = new MyThread();
//now cases where i got confused
//case 1
obj.start(); //it makes the run() method run
//case 2
obj.run(); //it is also making run() method run
}
}
so in above what is the difference between two cases, is it case 1 is creating a new thread and case 2 is not creating a thread ? that's my guess...hope for better answer SO guys.Thanks
start() runs the code in run() in a new thread. Calling run() directly does not execute run() in a new thread, but rather the thread run() was called from.
If you call run() directly, you're not threading. Calling run() directly will block until whatever code in run() completes. start() creates a new thread, and since the code in run is running in that new thread, start() returns immediately. (Well, technically not immediately, but rather after it's done creating the new thread and kicking it off.)
Also, you should be implementing runnable, not extending thread.
Calling start() will create a new execution thread, and then the run() will be executed in the newly created thread
where as directly calling run() will execute the code in the current thread
the simple answer to your question is this:
run(): runs the code in the run() method, blocking until it's complete
start(): returns immediately (without blocking) and another thread runs the code in the run() method
Calling start starts the thread. It does the underlying work to create and launch the new thread, and then calls run on that new thread.
Calling run just calls the run method, on the current thread. You never call run directly, use start.
run() method after calling start() : this is executed by your thread which is created by you, it is allocated processor to run independently.
run() method called by you : executed from your calling thread.
In one line directly calling run() is synchronous (your code will block until run() returns) and calling start() (your code will not wait for run to complete as it is called in other thread obj) is asynchronous.
When you directly use start() method, then the thread will run once using the Runnable instance you provided to it and then the thread will be unusable.
But to leverage the Thread Pooling and Scheduling capabilities that are inbuilt in Java, extending a Runnable or Callable is the way to go.
start() starts the thread. run() just runs the code, in the current thread.
Related
Let's say I have a runnable class with two methods:
class ExampleClass implements Runnable {
public void shutdown()
{
currentThread().interrupt();
}
public void run(){
while(!currentThread().isInterrupted()){
System.out.println("thread is running...");
}
}
And I go and implement the class somewhere like so and pass it to a thread:
ExampleClass object = new ExampleClass();
Thread sideThread = new Thread( object, "Side Thread");
thread.start();
object.shutdown();
Will all this object and all its methods be running on sideThread or is just the run() method of object on the side thread?
i.e. When I call shutdown() will it actually interrupt the sideThread or will it just interrupt on the main thread where the object is instantiated?
There's no additional magic in Runnable. A Thread takes a Runnable and calls its run method on a new thread. End of story. Any other methods on that object are none of Thread's business. If you want to provide tighter integration between the calling thread and the created thread, that's on you to design.
What Silvio Mayolo says is correct, any thread can call any method of an object, passing a Runnable to a thread's constructor tells the thread to execute that Runnable's run method. If you want you can pass the same object implementing Runnable to several new threads and let them all run it. No magic here.
When you call Thread.currentThread(), that returns the thread that is executing the code. So as your posted code works now, if 1) a thread A starts a new thread B passing in this Runnable, and next 2) thread A calls shutdown on the Runnable, the result is that the interrupt flag is set on thread A, not on the thread B, the one executing the run method. Probably not what you want. It would be better to keep a reference to the new thread, and call interrupt on that.
Each thread gets a name generated for it. Try adding some lines like:
System.out.println("thread=" + Thread.currentThread().getName());
in your code and it will show you which thread is executing. You will see the new thread executing the run method, and the thread that created the new thread running the shutdown method.
This question already has answers here:
What's the difference between Thread start() and Runnable run()
(14 answers)
Closed 8 years ago.
What is the need to run the thread through start method? Why not we call directly run method ?
What will happened if combined the code of start() and run()
to make it as single method run()
Dont explain the difference between both method, i want to know about this scenario.
When program calls start() method a new Thread is created and code inside run() method is executed in new Thread while if you call run() method directly no new Thread is created and code inside run() will execute on current Thread.
Each thread starts in a separate call stack.
Invoking the run() method from main thread, the run() method goes onto the current call stack rather than at the beginning of a new call stack.
Please refer What if we call run() method directly instead start() method? also read Difference between start and run method in Thread
You need to know that thread can have different states. Based on http://www.tutorialspoint.com/java/java_multithreading.htm there are 5 states of thread
new - thread was created and can be started
runnable - thread is executing
waiting - thread is waiting for other thread to finish; other thread will have to inform this thread that it finished by calling for example notify method on shared lock
timed waiting - similar to waiting but thread will stop waiting after some time automatically without waiting for signal from other thread
terminated - thread finished its task
run method contains only code which needs to be executed when thread will work (when it will be in runnable state).
start method is needed to take care of changing state of threat from new to runnable so it could start working and use its own resources (processor-time for instance) to execute code from run method.
When you call yourThread.run() code from run method will be executed by thread which invoked this method, but if you use yourThread.start() then code from run method will be executed using resources of yourThread.
Take a look at this example
public static void main(String[] args) {
System.out.println("main started");
Thread t = new Thread(){
public void run() {
try {Thread.sleep(2000);} catch (InterruptedException consumeForNow) {}
System.out.println("hello from run");
};
};
t.run();
System.out.println("main ended");
}
Code in run method will pause thread which runs it for two seconds (because of Thread.sleep(2000);) so you can see hello from run after two seconds.
Now output looks like this
main started
hello from run
main ended
because code in run method was executed by main thread (the one handling public static void main(String[] args) method), also because of two second pause part
hello from run
main ended
was printed later.
Now if you change t.run() to t.start() code in run method will be executed by t thread. You will see it by observing result which would be
main started
main ended
(from main stream) and after two seconds
hello from run
run() method defines what the thread will do. start() method starts the thread to perform its task implemented by the run method.
If you call the run method directly, it is performed by the caller thread. However, the start method causes to process the task in a newly started thread. In the former case, the caller thread waits for the run method to be completed. In the later case, on the other hand, the newly created thread executed asynchronously and so the caller thread continues its job without waiting the completion of the run method.
If you directly call the run() method of the thread then the code inside of that method will be run in the thread that calls the run() method. Calling start() will create a new thread and execute the code in the run() method on the new thread.
Put simply calling run() directly is probably a bug since you aren't actually creating a new thread.
See the following link for a reference.
http://javarevisited.blogspot.co.uk/2012/03/difference-between-start-and-run-method.html
In simple term
invoke Thread.start in order to start the new thread.
If you call run method directly then its just like a normal method call in the same thread.
What JavaDoc - Thread#start() states:
Causes this thread to begin execution; the Java Virtual Machine calls the run method of this thread.
see Defining and Starting a Thread a Java Tutorial
Read more...
I've been using threads for 2-3 days now, and I've got a quick question regarding methods. I'm making an Android application and it starts off with the main UI thread (let's call it the "UI Thread" for clarity). I'm spawning a new thread using the following code:
Thread thread = new Thread(new Runnable() {
#Override
public void run() {
someMethod();
}
});
thread.start();
My question is, will someMethod() also run on the new thread that I just created because I'm calling it from there? Or will it run on the UI thread? For reference, someMethod() is located outside outside of the method that's creating the new thread.
If someMethod() won't run on the new thread, how do I make it do so? Thanks.
will someMethod() also run on the new thread that I just created because I'm calling it from there?
Yes, that is exactly what happens. The method is just code. It's independent of the thread-of-control that happens to be running in it at a given point and time. This also means that there could be multiple threads executing that code at any given point in time if there are multiple cpu/cores.
You should take a look at Callable<V> and Future<T>, there you can call methods, that are not processed on the calling thread. You shouldn't work with threads anyway nowadays.
There are more modern approaches available.
Here is a link that should give you an idea http://www.vogella.com/articles/JavaConcurrency/article.html#futures
All of the actions taken by run, including calling someMethod, stay on the new Thread unless that code tells Java to run something in another thread (like with invokeLater or by using an Executor).
In java, does run() register a thread in a thread scheduler?
What about construct(),start() and register() ?
In java, does run() register a thread in a thread scheduler?
No. If you call the run() method directly, it is called as a normal method; i.e. it runs on the current thread, not a new one.
What about construct(),start() and register()
The start method creates a new thread, and in the process the thread will be registered with the scheduler. (However, the scheduler is a nebulous concept in Java. It is implied that one must exist, but its implementation and behavior are typically left to the host operating system. A pure Java program has almost no control over the way that the thread scheduler actually works.)
There are no construct() or register() methods in the Thread API. If you are referring to the Thread constructors, they only create a Thread object, and NOT the underlying thread that will do the work. The latter is only created when start() is called.
run() is the actual code in the thread; so you could do like:
Thread childThread = new Thread() {
public void run() {
// do stuff on a new thread
}
};
(Though I've been told extending Thread like that is ugly ;)
So calling run() itself won't create a new thread. To do that, you use start():
childThread.start();
So, I guess it does give the scheduler a new thread to deal with -- but that's way down on the OS level.
I'm not sure what you mean by construct() and register() though?
Please explain the output of the below code:
If I call th1.run(), the output is:
EXTENDS RUN>>
RUNNABLE RUN>>
If I call th1.start(), the output is:
RUNNABLE RUN>>
EXTENDS RUN>>
Why this inconsistency? Please explain.
class ThreadExample extends Thread{
public void run() {
System.out.println("EXTENDS RUN>>");
}
}
class ThreadExampleRunnable implements Runnable {
public void run() {
System.out.println("RUNNABLE RUN>>");
}
}
class ThreadExampleMain{
public static void main(String[] args) {
ThreadExample th1 = new ThreadExample();
//th1.start();
th1.run();
ThreadExampleRunnable th2 = new ThreadExampleRunnable();
th2.run();
}
}
The Thread.start() method starts a new thread, the entry point for this thread is the run() method. If you call run() directly it will execute in the same thread. Given that calling Thread.start() will start a new thread of execution, the run() method may be called after (as in you example) the rest of the main method executes.
Change your main method to call th1.start() and run repeatedly, you will see that sometimes it outputs:
EXTENDS RUN>>
RUNNABLE RUN >>
and sometimes it outputs:
RUNNABLE RUN >>
EXTENDS RUN>>
depending on how java chooses to schedule your 2 threads.
Check out the java tutorial on this.
When you call th1.run() you are running the run method in the current thread, so thus must happen before call to th2.run().
When you call th1.start() you the run method is being called on a new thread. In this case it is happening after the call to th2.run(). (In fact, it is theoretically possible that it could happen before the th2.run() ... but current and previous Sun implementations of thread.start() do not cause the current thread to immediately "yield" to the new thread.)
This illustrates a common mistake with using Java threads. If you want to run stuff on a new thread, you must call thread.start(). Directly calling thread.run() is almost always a mistake.
When you call .run(), the method is called and the code within executed the same as any other method. If you call .start() on a thread, though, the run() method will be run in that thread, and not sequentially in the main thread.
So when you call th1.start(), you have code executing in two threads at once: the main thread will go on to create th2 and then call its run method, while the th1 thread will call its own run method. There is no guarantee on the ordering of these, because they're executing in parallel.
executing run() is synchronous - executing start() is asynchronous.
The calls to run() are just a regular synchronous method call, and they happen in that order. Using th1.start(), a new thread is started - it's now a two horse rase - the two run methods are now executing independently - first one to the finish wins, and there is no guarantee about order.
But if the order is not guaranteed, why does the new Thread print later most of the time? In practice, it takes some time to start a new thread, so by the time it gets started, the other run() method has already ran. Even on a multi-core machine, where both threads can execute simultaneously, the new thread will typically come last, since the thread-startup involves more work.