which is the thread that will begin as soon as the execution of a java program begins?
This was asked in an interview for me.
so can anyone suggest the answer here
From Thread API document
When a Java Virtual Machine starts up, there is usually a single non-daemon thread (which typically calls the method named main of some designated class).
And this thread will be called as main thread.
The thread which is created when you start is called the main thread. It is the one which invokes the main method.
Edit: apparently someone beat me to the answer.
The 'main()' method in Java is referred to the thread that is running,
whenever a Java program runs. It calls the main thread because it is
the first thread that starts running when a program begins. Other
threads can be spawned from this main thread. The main thread must be
the last thread in the program to end. When the main thread stops, the
program stops running.
Main thread is created automatically, but it can be controlled by the
program by using a Thread object. The Thread object will hold the
reference of the main thread with the help of currentThread() method
of the Thread class.
for more details check this link
'Main' Thread in Java
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.
I have a few questions about Java multi-threading. I am currently learning different methods of multi-threading. My first question is, what happens to the thread after the code in it is done running? Do I need to Stop/Kill the thread? I am currently making a class for each thread and implementing Runnable in each class. I then start the thread in the main class using new ThreadClass();. In the constructor of the Thread class, I have it set to make a Thread named "second." If I add new ThreadClass() twice in the main method, are both threads named "second"? Thanks.
My first question is, what happens to the thread after the code in it is done running? Do I need to Stop/Kill the thread?
The thread stops when it has nothing to do. If you have an ExecutorService, you have to use shutdown when you have finished with it.
If I add new ThreadClass() twice in the main method, are both threads named "second"?
You are making the code the same. This doesn't mean the name of the thread has to be the same (and vice-versa)
I assume you mean Thread rather than ThreadClass.
When the run method of a thread returns then the thread will stop. If you only specify the name in the second thread then only that thread will have the name "second". The first thread is unaffected.
You should avoid calling stop if at all possible as it does not allow the thread to exit cleanly.
I was teaching myself Java threading and I noticed something that confuses me a little. I made a class called engine implementing Runnable. The run method just prints "Hello World", sleeps for a second, and repeats.
In my main method, I have:
public static void main(String[] args) {
Thread thread = new Thread(engine);
thread.start();
System.out.println("Done.");
}
As I expected, I see "Hello World" and "Done." printed quickly, meaning the main method has reached the end, but what I didn't expect was that the thread I started kept running even after the end of main was reached.
Why does the program continue to execute even after main exits? I would have thought that when main exited the process would terminate and all of the threads would be cleaned up forcefully. Does this mean that every thread has to be joined/killed explicitly for a Java program to terminate?
Because that's how it works. The program exits when System.exit() is called, or when the last non-daemon thread stops running.
And it makes sense. Without this rule, every Java program consisting in just spawning a GUI, for example, would have to wait() infinitely to avoid the program from exiting immediately.
If you want your program to exit when the main method finished, consider making your threads daemons. But take care of the fact, that daemon threads will be aborted, when main finishes.
You can create a daemon thead like so:
Thread t = new Thread(...);
t.setDaemon(true);
All non-daemon threads are user threads. Those threads are stopping the jvm from closing.
User threads continue to run independently of the lifetime of their parent thread, i.e, the creator thread. So, you have to join the threads explicitly by invoking Thread.join before the main thread terminates.
From the Javadoc of Thread:
When a Java Virtual Machine starts up, there is usually a single
non-daemon thread (which typically calls the method named main of some
designated class). The Java Virtual Machine continues to execute
threads until either of the following occurs:
The exit method of class Runtime has been called and the security
manager has permitted the exit operation to take place.
All threads that are not daemon threads have died, either by returning
from the call to the run method or by throwing an exception that
propagates beyond the run method.
If you want JVM to terminate even if a thread t is running, you should make thread t a daemon thread:
t.setDaemon(true);
There are two types of threads, user and daemon. The process terminates when there are no more user threads. The main thread is always a user thread. The thread that you start is also a user thread, and therefore keeps the process alive for as long as it runs.
Calling setDaemon(true) on your thread before you start it will make your process terminate (more or less) as soon are your main() function returns.
The Java Language Specification section 12.8 indicates:
12.8. Program Exit
A program terminates all its activity and exits when one of two things
happens:
All the threads that are not daemon threads terminate.
Some thread invokes the exit method of class Runtime or class System,
and the exit operation is not forbidden by the security manager.
This means it is not enough for the main thread to finish.
If you do want it to exit when the main thread ends you need to either make the new thread a daemon by using Thread#setDaemon or use Thread#join as you initially suggested.
The main thread is also a user thread which is being created and its lifecylce is similar to any other user thread for that matter.
The other user threads are not dependent on the main thread for any reason unless you set the threads as daemon threads.
Once the main thread completes its work it ends(it neither ends the other user threads nor will end the process because the other user threads are running).
Doing some studying about threads and I'm confused about what the start() method in Java threads actually do.
My current understanding is that the start method doesn't immediately start the thread's execution, but instead moves it to a pool of threads waiting for it be picked for execution by the thread scheduler.
Is this correct? I can't seem to find any good resources about what the methods actually do.
Exactly, when a call to start() is performed, it just schedules the call to run(). You cannot determinate when the thread will effectively be launched, nor when it will effectively be stopped.
You can find more information in the Java Doc on oracle's website.
start
public void start() Causes this thread to begin execution; the Java
Virtual Machine calls the run method of this thread. The result is
that two threads are running concurrently: the current thread (which
returns from the call to the start method) and the other thread (which
executes its run method).
Throws: IllegalThreadStateException - if the thread was already
started. See Also: run(), stop()
Source
You are confusing Threads with ThreadPools
A thread is an "unit of execution", code executed on a separate thread runs in parallel with your main programs when you call start()
ThreadPools is a mechanism built on top of threads, it allows you to create a group of threads which will take care to execute tasks you submit to the ThreadPool queue.
Yes, this is correct. You don't know when this thread will be executed but for sure it is scheduled for running.
Have a look at the following picture. It explains the lifecycle of a thread: http://cs.fit.edu/~ryan/java/language/thread.gif
start immediately starts the new thread, but by the very nature of threads, there is no guarantee as to when any line of code in that thread will actually execute. It is not appropriate to use the term "thread pool" in this context because the concept of a pool involves resources that are reused between user-requested tasks. A Thread instance is hardwired to a single invocation of the run method, after which the thread dies.
The thread scheduler is a native OS-level component and is not under the direct control of the JVM.
When you call Thread.start it makes a special instarcution to JVM for starting a thread and JVM will taken care of its life cycle.
Java Thread can have begining,end and sequence,What does that mean?
I think all it means is that a thread executes a sequence of actions. It's expressing that concept pretty badly, to be honest.
In other words:
You create a Thread, ideally passing it a Runnable. (You can extend Thread instead and override its run method but that's generally frowned upon.)
You call start on it
The thread which called start continues executing the next statement in its program
The run method executes in the separate thread, independently of the thread that started it. The behaviour in here is what I believe is meant by the "sequence"
The new thread eventually ends due to one of the following conditions:
Its run method completes normally
Its run method completes with an exception
If it's a daemon thread, it can terminate as part of the JVM terminating due to all the non-daemon thread exiting