Little confused about multi-threading concepts - java

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.

Related

i'm so confused about Threads

I read a lot about threads but don't understand yet :( let me explain to you what I have learned about threads. all we are working on such as codes any thing worked on UI thread or Main thread right? After that what happens if we call runOnUiThread? and my other question how do we know it's Time to use a new thread? I mean how do we understand we are working on another thread or replace or code in the new thread?
I know this is an unclear question but I don't understand as well. Please help me Thanks, john.
Let me try to answer. Actually Android has Main Thread (also called as UI Thread) and other thread.
Main Thread is basically for showing UI and other thread is for processing other big processes such as connecting to the server, etc.
runOnUiThread is called when you want to move from other thread to main thread. It is needed since only main thread can show/display result on UI. So when you have done some process on other thread, and you want to display the result on the apps, you need to show it on main thread by calling runOnUiThread.
We working on other thread only if it is a big or lengthy process like taking data from the server, load data, etc. And we move from other thread to main thread whenever we want to show some UI result.
Easiest way is to use AsyncTask<> class. You'll need to override three functions.
doInBackGround(...) : The codes that gets executed in background thread.
onPreExecute(..) : code that gets executed before background thread
completes executing like displaying progress bars, etc.
onPostExecute(...): Code that gets executed after background thread
has completed running. Perform task like updating UI in here
One general rule of thumb is: Don't use multithreading if you don't need to. Multithreading is always error-prone, and in many situations there's no benefit. Basically, you start a new thread whenever you execute a lengthy operation (i.e. some extensive computation like image processing) that would block the main thread for some time, so the application would become unresponsive.

Threads ends when run finish? [duplicate]

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.

clarification on the concept of Java thread

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

Is it wrong to do runnable.run()?

I am fairly new to the concept of multithreading and there is an aspect which is not clear to me.
There are two ways to create and run a thread:
Extend a Thread class and start() the thread.
Create a Runnable object, pass it to a Thread constructor and start() the thread.
And this blog post states that we always should start a thread using a start() or so was my impression of it.
But in one of the answers here you could see how a person is using runnable.run(). It gives me an impression of somewhat wrong practice.
Is it normal? Should it be avoided? You can be explicit in your answer, but any suggestions would be appreciated.
They're just different things. run() executes the Runnable in the current thread. Calling start(), on the other hand, causes the Runnable to run in the new thread.
The tutorial points it out as a pitfall. You went through all that trouble to make a thread, so if you go on to run it in the current thread instead, then it's likely a mistake.

What is the meaning of sequence in java?

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

Categories