in the main method if I write this:
Thread aThread = new Thread();
aThread.run();
what will happen???
It will run in current thread. You will not start new thread this way.
But that doesn't really matter in your example since you gave new Thread no code to run anyway.
The thread that runs the main() code is the current thread. Creating a Thread object and calling one of its methods (other than start()) is like calling a method of class Integer or String - it doesn't create a new actual thread.
In your code example, execution of the main method will continue only when the run() method has finished running. This means that if the run() method has an endless loop (let's say it's waiting for incoming requests), then the main() method will never continue running, even if there are more lines of code after the call to run().
Calling aThread.start() creates a new actual thread (represented by the object aThread), makes the new thread call the run() method, and returns execution of the original thread to the next line in the main(). This means that the new thread can run around in circles forever, but it doesn't stop the main() code from creating more threads or performing other tasks.
It will just run like you're calling a normal method. So the method will be running in the same thread that calls the method.
It will run in the current Thread not in new Thread So If you call run method yourself it is meaningless. Because It doesn't create a new Thread.
If you call the start-method on a Thread class, the start-method will return after a while, but in concurrency will run the content of the run-method. If you call the run-method directly it will be executed and return to the caller, after the method is completely done - as every normal method call.
Related
How can I call and run a method on the main thread, called from its worker thread?
Main Thread code, (Foo() function is accessible from Main Thread):
Thread newThread = new Thread(myThread, myThread.getThreadName());
newThread.start();
Worker Thread code (newThread):
#Override
public void run(){
// need to call from here Foo() function - it has to run on the main thread
}
Thanks!
The words "call a method in another thread" have no meaning in Java.
You need to understand that Thread and thread are two different things: A thread is a path of execution through some code. A Thread is a Java object that can be used to start a new thread and manage its life cycle.
A new thread begins when some other thread calls t.start() where t refers to a Thread object. The thread begins executing the t.run() method, and it wanders into and out of function calls until it reaches the end of t.run(), at which point it dies. Meanwhile, other threads are following their own paths through the code.
At the lowest level, the only way for one thread to interact with another is by updating the fields of shared objects and classes.
Thread A can tell thread B to execute some function or another by sending a message (i.e., by updating a field in some object), but thread A can never make thread B do something. Thread B can only do what the code it is executing says to do. If the code says, look at field f, and if its value greater than zero, then call function foobar(), then that is what thread B will do. Or if the code tells it to pop a Runnable off of a queue and call the Runnable's run() method, then that is what the thread will do.
But no thread can change the code that some other thread is running once the thread starts running it. It can only change fields that influence what the code will do next.
Is there any difference between creating a thread using the run() method as opposed to using the a constructor?
I noticed that I can start the thread and it acts the same in both ways.
new Thread MyThread().start
For example, as a constructor:
public class MyThread extends Thread{
public MyThread(){
// Do something
}
}
or as the run() method
public class MyThread extends Thread{
public void run(){
// Do something
}
}
Is there any difference between constructor or run()? Thanks!
It does not act the same in both cases
These cases are entirely different.
First, you probably need to learn about Threads and non-blocking processes. A Thread is used to do something asynchronously. So if you wanted to do some background task whilst doing something else then you would use a Thread. A good example is a GUI; you need one Thread to listen for GUI events (mouse clicks, button presses) and another to do any long running processing.
Now, onto your examples.
In Java a Thread consists of a run method that executes asynchronously when the start method is called. So when overriding Thread you change the run method. In reality you should never override Thread, you should use the constructor that takes a Runnable. There are many reasons for this, you should read up on concurrency.
Any code you place in your Thread constructor will be executed in the Thread that calls your constructor so this is not called asynchronously.
If you put the code in the run method, a new thread will be started upon invocation of start, which uses the run method as its starting point. If you put the code in the constructor, however, it will be run in the same thread as that which invoked the constructor, because a constructor is a special case of a method. Thus, if you want to start something in a new thread, put it in run, otherwise, put it in the constructor. Also, if you want to start a thread, never call Thread.run, because of the same reason not to put code in the constructor. Always call Thread.start().
The key difference is this:
The code in your constructor is executed immediately and synchronously when the constructor is invoked.
The program will stop and wait for that code to complete before moving on to the next line of code.
If you put the code inside run() method AND use Thread.start(), the code will be executed in a separate thread (i.e. it will run asynchronously).
Your program will continue to execute (moving to the next line of code immediately) while the code in your run() method runs in parallel.
This is helpful if the code in run() takes a very long time to execute.
That's because your program can continue to do other things while it waits for the thread to finish its work.
There is a difference. The constructor that creates the Runnable or subclass thereof runs in the main thread.
When starting a thread using:
new Thread(myRunnable).start();
you'll actually have run( of myRunnable run in the new thread.
NB You'll want to have a reference to the thread object in many cases. This code example is merely illustrative
On another note, never, ever, ever, give a thread this if starting within a constructor. Your computer could explode, or asphyxiation, drowning, or poisoning may occur.
When we invoke the start() then a new thread of execution starts with dedicated call stack.
I'm wondering which is going to be the first method in that call stack: start() or run().
It's mentioned that the Thread is considered to be dead once run() completes.
start is a method call on the main thread. This means it is on the stack of the main thread. Then inside start a new thread is actually fired and the run method is the first method on the new thread's stack.
start() isn't called on the new thread at all; it only runs on the original thread.
I can create a class which extends Thread and overrides the run method with a loop.
I then start it with myThread.start(), which create the OS thread and executes my run().
That's all good.
However, I don't quite understand the details. I'll have a go at working this out using test code when I get the chance, but before then can anyone answer these:
Q1. When does the constructor get executed, presumably when myThread is declared, or on start()?
Q2. What happens when my run() code completes? Is there a way of getting it to run again in the same thread (i.e. not losing all the thread variable values defined in class) Presumably calling start() might create a new os thread?
Q3. Presumably just calling myThread.run() would execute my run() in the context of the current activity, not mythread, in which case how could it access the thread variables?)
-Frink
A1) When you construct the instance of your MyThread class
A2) Threads cannot be run twice or restarted, as stated in the documentation.
A3) Yes, calling run() directly will execute that function in the current Thread, not in a new Thread. It doesn't make much sense to create a class that extends Thread if you want to just call run(). You should always call start().
Why do we need to run the thread through start method and not directly through the run method ?
The run method just executes the thread's task in the current thread. Historically, you would subclass Thread and override run - although today the preferred mechanism is to pass the Thread constructor a Runnable. So run itself doesn't do any threading - it's start which creates a new "actual" thread (as opposed to just a Thread object) and makes it execute run() when it's started.
Because the run method contains the code that the new thread should execute.
If you were to call the run method, then you'd just execute it on the current thread.
Calling start starts the new thread and then executes the run method on the new thread.
The start() method tells the JVM that it needs to create a system specific thread. After creating the system resource, it passes the Runnable object to it to execute its run() method. Calling the run() method directly has the "Thread" execute in the same thread as the calling object, not in a separate thread of execution, as intended.
In other words, calling run() is just like a normal method call. Whereas, calling start() tells the thread to create the necessary system resources and then execute the run() method asynchronously.
EDIT:
For example,
Pseudo code1:
thread one = new thread();
thread two = new thread();
one.run();
two.run();
This makes the threads run sequentially,ie, two.run(); will run only after one.run(); finishes.
Pseudo code2:
thread one = new thread();
thread two = new thread();
one.start();
two.start();
In this case both threads start and run simultaneously.
The start() method calls the run() method asynchronously (doesnt waits for any result, just fires up an action), but when WE call run(), it runs synchronously, ie,it waits until run() finishes and only then it proceeds to the next line of code.
in java Thread is always created in Stack Memory.When you create a new Thread it takes new memory in Stack.When you call start() method it initialize in new Stack Memory and when you call run() method it initialize in same Stack Memory
That is why we always call a Thread with start() method