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
Related
This question already has answers here:
Do java threads get deleted when they finish
(3 answers)
Closed 7 years ago.
I want to know if a thread in java closes itself when run method ends.
I mean, I have a new thread declaration:
new Thread(new SubmitDataOnBackground(handler.getIDValue(), data, this.context)).start();
And then, in SubmitDataOnBackground I have this run method:
public void run() {
SubmitDataHandler submit = new SubmitDataHandler(ID, data, this.context);
submit.buildAndSubmitData();
}
After buildandSubmitData finishes, does the thread close itself or I have to add any code somewhere?
I am not sure if I am leaving a new thread opened each time I call this method or it is ok.
My application is a server so it will never ends because it is active the whole time. I just want to know the amount of threads is not outnumbered because it just creates new ones without closing the others when finish.
Threads close themselves after the run method has been called. Read this for further information https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html
EDIT: If you want to avoid this behaviour, I recommend using ThreadPools.
Yes, a thread finishes when run() method execution ends. You can read more on threads and concurency in general here
One tip here - when using multiple threads that are started and finished all the time, it is a good idea to use a thread pool. That is because creating a thread is quite a heavy operation.
Threads are terminated after finishing their jobs (when the execution of run() ends). If you want to check, use isAlive().
Yes, threads are terminated after finishing their specified jobs (sequence of instructions) in run() method.
However, the thread object that has been created still exists, allowing you call it again with Thread.start() to create a new Thread.
If you want to be sure that your thread run method ends before continuing doing something more, try to use the method Thread.join() in the same place where you are working with threads.
Read this for further information about that:
https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#join%28%29
In order to actually make a Thread stop itself, the process is quite simple. All you need to do is simply let the run method run out and return.
public void run(){
// implement your code
// Just about to return and the Thread will then stop soon after
}
Note that the thread will not necessarily be declared finished immediately after the run method has finished, as the Java Virtual Machine (JVM) still needs to finish it off in the background, but it should terminate completely soon after.
In other words, when a normal Thread (also referred to as a user Thread) is created, it is expected that it will complete its work and not shut down permanetly. The JVM will not terminate until all user Threads have finished, or until a call is made to the System.exit() method, which terminates the JVM abruptly.
EDIT: System.exit() does not stop the JVM abruptly, it executes all the shutdown hooks first. Runtime.getRuntime().halt() stops the JVM without any further processing.
Is there any way I can stop a thread without using deprecated stop()?
The thread invokes some methods from a potentially badly written class which may contain infinite loops. Since I can't modify this class, I have no control over the loop condition and therefore can't exit normally using interrupt() or any other variable. Is it justified in this case to use stop()?
If you cannot use stop() and cannot fix the code, your only other option is to run the code in another process and kill the process.
In your case, the simplest option is to use Thread.stop()
The problem with the stop() method is that it can leave synchronized objects in an inconsistent state (i.e. if you stop the thread while you're halfway through a synchronized object update, then only part of the object may be updated). If your thread isn't using any synchronized methods / blocks then it's safe to stop it.
If your thread might be using a synchronized block/method, then try to cleanly shut it down before calling stop, e.g. call interrupt on it and then call stop X minutes later if the thread still hasn't stopped (operating on the assumption that the thread is calling a broken method). Just be sure that the thread leaves everything in a consistent state before calling a potentially broken method.
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.