This question already has answers here:
termination of program on main thread exit?
(2 answers)
Closed 7 years ago.
will main thread exit before child threads complete execution?
i read in 2 articles
http://www.cs.mtu.edu/~shene/NSF-3/e-Book/FUNDAMENTALS/thread-management.html
in the above article, In "Thread Termination" para, it states in Red " if the parent thread terminates, all of its child threads terminate as well."
http://www.roseindia.net/java/thread/overview-of-thread.shtml
in the above article, the last line in that page states "The main() method execution can finish, but the program will keep running until the all threads have complete its execution.".
i fee they are contradictory. if i am wrong, Please experts correct me.
In my program, a program with Main method calls the constructor of 2 threads . in the constructor of the respective threads, i am having the start() method .
TestA A = new TestA("TestA");
TestB B = new TestB("TestB");
public TestA(String name) {
System.out.println(name);
t = new Thread(this);
t.start();
}
i would like to know what happens, main thread terminates before child threads complete execution? if so, will the child threads anyway, continue their execution??
i tried running the program, some times all the child threads are getting executed complete even if the main thread exits.
In the 2 threads , i am processing some files. in testA thread A alone, 1 file alone is not getting processed some times. but many times, all the files are getting processed and i do not have any issues.
Java makes a distinction between a user thread and another type of thread known as a daemon thread. The difference between these two types of threads is that if the JVM determines that the only threads running in an application are daemon threads (i.e., there are no user threads), the Java runtime closes down the application. On the other hand, if at least one user thread is alive, the Java runtime won't terminate your application.
When your main() method initially receives control from the Java runtime, it executes in the context of a user thread. As long as the main-method thread or any other user thread remains alive, your application will continue to execute.
In your case, the threads are user threads and hence are allowed to complete before the main thread exits.
i am processing some files. in testA thread A alone, 1 file alone is
not getting processed some times. but many times
The reason for the above is could be something else than thread exits. It could be file locks, synchronization issue etc.
Thread (Java SE 10 & JDK 10):
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.
The background threads will keep running, even if the MAIN thread completes.
If you want MAIN to stop them (example, when MAIN is complete), have your MAIN set a "keep running" flag variable (which you must set as "volatile"), which the threads occasionally look at. MAIN sets it to false (variable) or null (object) when MAIN wants to stop them. When it's false or null, then the thread must "return;".
This is somewhat complex to implement, there are many ways, but easiest is to make your Runnable an inner class, so that your Runnable has easy sharing of the flag.
For the best implementations, look up this technique in Java applets' start/stop routines.
Once the main thread exits, it takes the children with it. Perhaps by "finish" the second article simply means no more operation other than waiting for the children. Once the main thread calls System.exit(0); it's over -- every body dies.
Say you have two threads running: threadA and threadB. in the main method. The first code is the nice way of terminating the thread -- just one of many ways:
threadA.start();
threadB.start();
final long intercept = 300;
long startTime = System.currentTimeMillis();
while (threadA.isAlive() && mis.isAlive()) {
threadA.join(intercept);
if (System.currentTimeMillis() - startTime > intercept) {
threadB.interrupt();
threadA.interrupt();
threadA.join();
}
}
System.exit(0);
Below is an abrupt way of killing all threads from within main:
System.exit(0);
Related
I read this statement:
The main thread must be the last thread to finish execution. When the main thread stops, the program terminates.
Is it true?
I also came to know "Even if the main thread dies, the program keeps running".
This is my current understanding:
When you start a program, the JVM creates one thread to run your program.
The JVM creates one user thread for running a program. This thread is called main thread.
The main method of the class is called from the main thread.
If a program spawns new threads from the main thread, the program waits until the last thread dies.
Which one is true?
The program terminates when all non-daemon threads die (a daemon thread is a thread marked with setDaemon(true); it's usually used for utility threads). From the documentation:
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.
I read this statement: “The main thread must be the last thread to finish execution. When the main thread stops, the program terminates.”Is it true?
No, it is not. The virtual machine terminates if the last non-daemon thread has finished. It doesn't have to be the main thread.
Simple example:
public static void main(String[] args) {
System.out.println("Main thread started");
new Thread(new Runnable() {
#Override
public void run() {
System.out.println("Second thread started");
try {
Thread.sleep(2000); // wait two seconds
} catch(Exception e){}
System.out.println("Second thread (almost) finished");
}
}).start();
System.out.println("Main thread (almost) finished");
}
When the main thread stops, the program terminates.
The program terminates when there no longer is any non-daemon thread running (or someone called System.exit). The main thread can have finished long ago.
The JVM will exit when the main thread and all non-daemon threads finish execution.
When you create a new thread, you can call Thread.setDaemon(true) to make it a daemon thread. If you do this, then the JVM will not wait until this thread finishes before execution. This is useful for any threads you create which are made to run in the background until the program stops.
If you create a new thread and do not call Thread.setDaemon(true), then the JVM will delay exit until this thread is complete, even if the main thread is finished.
When the main thread was start it'll not wait for the another thread which was created by us until they if can't use the join() of the thread class to wait for this thread. So basically if the child thread or sub thread getting more time for processing the task and you don't use the join() then main thread may be stop. To keep with main thread you must use the join() so the main thread stop after only this related thread are stop
check this link
http://download.oracle.com/javase/1.5.0/docs/api/java/lang/Thread.html#join%28%29
The first statementis not exact.
The java program terminates when all non-daemon threads has been terminated or when System.exit() or Runtime.exit() is invoked.
Thread is terminated when it exited its run() method. Main thread is special because you do not explicitly implement its run() method, you implement main() instead and the main() is called from run(). So, main thread is terminated when main() is terminated.
But main thread is not neccessarely the last one.
This is the from the JVM specification 3rd Draft, so it's the most current I'm aware of:
5.7 Virtual Machine Exit
The Java virtual machine terminates all its activity and exits when either:
• All threads that are not daemon threads terminate.
• Some thread invokes the exit method of class Runtime or class System, and
the exit operation is permitted by the security manager.
There is no distinction made about the main thread, so we shouldn't assume that is the only one that it applies to.
This question already has answers here:
How Thread run starts?
(5 answers)
Closed 8 years ago.
....As the title of the questions says, I want to know what all things internally happen when we call Thread.start() and when does the start method return and main resume to execute. What all things internally get triggered like registering the thread with scheduler etc..? Also why executors are used ?
When you call t.start the JVM creates a new thread of execution (with its own stack). This is done by native code, it is not done in Java. So then the JVM itself calls t.run in the newly created thread of execution. This is usually a source of confusions (for starters) as the Java class Thread has the same name as the concept thread of execution. I guess one can think of these two as: the latter is the 'physical concept', the former is its 'abstract Java representation as a class'.
It usually takes some time between you calling t.start in the current thread of execution, and the JVM calling t.run in the newly created thread of execution; there's some time lag there as creating a new thread of execution is a somewhat heavy operation.
Thread.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).
It is never legal to start a thread more than once. In particular, a thread may not be restarted once it has completed execution.
public void run() {
assignPlayer();
for(int i = 0; i < numPlayers; i++) {
PlayerListener listener = new PlayerListener(fromPlayer.get(i), this, i);
new Thread(listener).start();
}
return;
}
I am implementing a socket game. Every game has 2 players, and every game is given its own thread. the above run method assigns PlayerListener(which is a Runnable object) to each player for listening their incoming outputstream and calls some method from the game object if there is action to perform. Everything runs fine, but I was thinking about when will my game thread dies, so I intentionally set "return" after the PlayerListener assignment is finished ( but I think after the assignment is finished, there will be no statement so the run method will run anyway ). Anyway, my game is still running, shouldn't my thread dies and my game object dies along with it?
It is because the PlayerListener objects still calling the game object's method from time to time so the object does not get garbage collected??
I read the post When does a Java Thread reach the 'Die' State. It states that "If the run() method returns", so I was curious...
so I intentionally set "return" after the PlayerListener assignment is finished
Your return; is extraneous since it's at the end of the method. The method would return without it. The only time a thread will wait for the threads it forks is if you specifically call thread.join() on each of the threads.
Anyway, my game is still running, shouldn't my thread dies and my game object dies along with it?
The threads that you fork are most likely non-daemon threads. Daemon threads exit when the JVM exits but the JVM waits for all non-daemon threads to exit on their own. When you fork threads they take on the daemon status of the thread that forked them. If you want these threads to quit once the run() method finishes then say something like:
Thread thread = new Thread(listener);
// make sure the threads will be killed when all other threads finish
thread.setDaemon(true);
thread.start();
I read the post When does a Java Thread reach the 'Die' State. It states that "If the run() method returns", so I was curious...
Right. If you are in a thread's run() method, then that thread will finish if the run() method finishes. However, again, the threads that are forked in the loop will keep the application running unless they are specifically set as being daemon threads.
The "return;" statement does nothing, since it's at the end of a void method (and the compiler automatically adds code to a void method as if there were a "return;" statement there).
You haven't really asked a clear question. Are you asking why the program doesn't terminate?
You didn't explain how this particular "run()" method gets called. Only if it is the run() method of the thread itself, and called as part of the thread starting, will its return cause the thread to die.
Furthermore, the process will not die as long as there is at least one non-daemon thread running.
All in all, you have provided a patchwork of partial information, and a patchwork of partial questions. Connecting those two patchworks is beyond the abilities of Agatha Christie, let alone anyone with perfect knowledge of Java, let alone people on this site.
There are 3 threads: Main Thread (thread from which main() runs on), Thread A and Thread B.
Order of Operations:
Program Starts (main())
Main Thread instantiates and starts Thread A.
Thread A after X seconds instantiates Thread B.
Thread B is started.
Thread B after X seconds instantiates Thread A.
Thread A is started.
If the call to Thread B is the LAST statement executed in the runnable of Thread A, will Thread A terminate after Thread B is instantiated and started? Or will Thread B be nested in Thread A and therefore create an infinite number of nested threads? What is the default behaviour and how would I accomplish NOT creating an infinite number of threads (I would like every previous thread to end while the child survives).
A Thread.join() would cause the thread to wait until the children thread die, correct?
If this is just bad practice in general, can anyone recommend alternatives that will essentially accomplish the same task? I need one function to, after a few seconds, call another functions which will then run simultaneously with the first function. The first function will then, after completing some commands, die. The second function should then, after a few seconds, call a new instance of the first function. This loop should continue until aborted by the main thread (or until the program exits).
Your question contains the answer: you are thinking of threads as tasks or "functions to run", which they are not. Threads execute tasks, so design your code around the idea of tasks that can create other tasks. Tasks are simply Objects that implement the Runnable interface, nothing more. You can construct these tasks (or runnable objects) with all the data they need, even including references to other (parent) tasks.
Create one CachedThreadPool and whenever a task is ready to be executed, dump the task in the threadpool using the execute method.
One thing you will need to consider is program shutdown: you need to close the ThreadPool in order to close your program gracefully. You can simply call shutdownNow, but you'll probably want to device a technique that gives important tasks a chance to complete and then shutdown. That will take some practice to get it right (shutdownHooks for example are not easy), but from then on you can re-use it whenever you need more than 1 thread.
So I am trying to work with threads for a game I am making. I am very new to the subject so I may not understand correctly. My question is how does the currentThread() method work in the Thread class of the java API. The API says "Returns a reference to the currently executing thread object.", but as far as I understand multiple threads run at the same time. How is it possible to return only one executing thread?
The code that calls currentThread will be executing in one of the threads, not in all of them, so it can get that thread specifically.
Suppose you have list of instructions printed on a piece of paper. A person reads the instructions and performs them. The instructions are a program. The person is a thread. You could make many copies of the paper and pass them out to many people. If the instructions say something like, "slap yourself," yourself refers to whomever is reading that instruction from that paper. Likewise, Thread.currentThread() refers to the thread that is executing that call to currentThread().
When an instruction in your code is executed, it is executed within a specific thread. This is the thread returned by that method.
Obviously, if a specific method is executed by multiple threads, each execution might return a different value for Thread.currentThread().
You could try this short example to get a better idea of what is going on and in particular the fact that the 2 threads execute in parallel. You should see that t1 will run a few loop then t2 will do the same and back to t1 etc (you might need to increase the number of loops from 5 to a higher number depending on your machine):
public class TestThread {
public static void main(String[] args) {
Runnable r = new Runnable() {
#Override
public void run() {
for (int i = 0; i < 5; i++) {
System.out.println(Thread.currentThread());
}
}
};
Thread t1 = new Thread(r, "t1");
Thread t2 = new Thread(r, "t2");
t1.start();
t2.start();
}
}
"The currently executing thread" means that the system scheduler gave some time to this thread to execute its code.
When writing a single threaded application, you can reason on your program like a series of instruction, each executed after the previous one is finished (this is a rough approximation, but conceptually compilator and processor try to simulate that and work as if this was really what was happening).
When you use multiple thread, each thread has its own series of instruction. A new thread when created is passed a entry point (a method), and will continue executing from them. Each thread is independent from the other thread in their execution (it will simply execute one instruction after the other), though they share memory and thus side-effect from one thread can affect another.
So for some code to be executed, it must be done in the context of one thread (there is one created by the operating system when your application start, that start its execution at the Main method). When the function currentThread is called, it is in one of those context.
The java runtime when creating a thread will store a reference to that Thread object in the thread context, and the currentThread will just lookup there and return the current thread.
At any given point in time, only one thread will be executing(live), so Thread.currentThread() returns the details of the currently executing Thread. e.g., Thread_name, priority, method_name.
Multiple threads are not running at the same time and there is thread switching between multiple threads. Processor can execute one task at a time so one thread at a a time executed. So we get the reference of currently running thread.