This question already has answers here:
How to know if other threads have finished?
(12 answers)
Closed 8 years ago.
I have a method that can take time to complete as it uses the internet to check something and depending on the internet speeds can take a while so I have placed it into its own thread but I'm wanting to know how I can notice when this thread is complete as I then need to update the screen from the Main thread.
New thread code looks like this:
Thread newThread = new Thread(){
#Override
public void run() {
//My thread code
};
newThread.start();
This is what the thread code looks like, not going to copy and paste all the code it uses as it would be pointless but I'm wanting something like when
newThread.iscomplete {
//More code
}
Something along those lines
Thanks
Maybe you can show a message at the end of the Thread. Which would be helpful to let the user know that the process has finished.
Showing Message
System.out.print("Thread has finished!");
This would be at the last line, so it would only execute if all the above codes have been executed and the code has reached the last line for execution.
Thread newThread = new Thread() {
#Override
public void run() {
//My Thread code
System.out.print("Done!");
}
};
This will print Done! in the Console (I assume application is being run using a Console). Denoting that the code has been executed.
using a variable
boolean done = false;
Thread newThread = new Thread() {
#Override
public void run() {
//My Thread code
done = true;
}
};
Using EventListeners
Or else you can use Event Listener to detect the Thread completion. The above method was kind of simple.
http://docs.oracle.com/javase/tutorial/uiswing/events/
Related
I have 2 question regarding on Thread, I just want to clarify something. With the below code:
public class MyThread implements Runnable {
Boolean StopThread = false;
Boolean DontLoop = false;
public MyThread(){}
public void Stop(Boolean stopThread){
this.StopThread = stopThread;
}
public void ThreadDontLoop(Boolean dontLoop){
this.DontLoop = dontLoop;
}
public void run(){
if(dontLoop){
while(true){
if(StopThread){
break; //Terminate WhileLoop, This will Stop and destroy the Thread also
}
}
}else{
//Does this mean the Thread will be destroy/terminate after this condition?
}
}
}
In order to Start:
MyThread myThread = new MyThread();
Thread thread = new Thread(myThread);
thread.start();
In order to Start Thread but Don't Loop
ThreadDontLoop(false);
thread.start();
In order to Stop the Thread
myThread.Stop(true);
Now, According to this LINK, that's how the thread to be stopped.
So my first question is, in the Given code above, what if I call ThreadDontLoop(false); then thread.start();, does this mean the Thread will Start but after the condition, the Thread will be stopped and destroy?
Second question is, Let's say I call thread.start(); then later I call myThread.Stop(true); to stop the WhileLoop and Destroy the Thread.
I didn't follow on how the link is stopped the thread since I will have a different condition, but I believe that the logic on how I would like to stop the Thread is correct?
You need a volatile boolean or the value can be inlined and never appear to change.
in the Given code above, what if I call ThreadDontLoop(false); then thread.start();, does this mean the Thread will Start but after the condition, the Thread will be stopped and destroy?
Yes.
Let's say I call thread.start(); then later I call myThread.Stop(true); to stop the WhileLoop and Destroy the Thread. I didn't follow on how the link is stopped the thread since I will have a different condition, but I believe that the logic on how I would like to stop the Thread is correct?
If you don't have a visibility issue (does the thread see your change) it will stop. In the code you have in the question, most likely the code will be optimised to assume the thread never sees the change.
how do we does that because i failed to google it. my attempt to make below statement working also return error. Could someone show me the way.
Thread[] = {Thread(calculateFile)} //wrong
//thread class
class calculateFile implements Runnable {
}
public void run() {
//do some stuff
System.out.println("do some stuff");
}
additional
actually i have a group of thread that run concurrently, i have to wait for all the thread to finish running and then run other program after that. i believe part of doing that i have to put all the thread into array first
I think you forgot variable name and new keywords.
Try something like this:
Thread[] myThreadArray = {new Thread(new CalculateFile())};
Also your calculateFile class has incorrect brackets, try this:
//thread class
class CalculateFile implements Runnable {
public void run() {
//do some stuff
System.out.println("do some stuff");
}
}
PS: good convention is to start class names with capital letter.
If your goal is to wait for all threads to finish their work before proceeding further, you are not forced to put all threads in an array, nor doing so will halt your code until all threads are done. What you need to do is join each thread on your main thread.
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I have some questions about java threads:
if I have a class that runs a number of threads when one thread reaches to exit(1) command line will it exit the thread or the whole application including the other threads?
2.how can I make one thread notify all other threads that run from the same class to stop?
3.does using synchronized make only one thread ,regardless his source in the code, to do this part of code?
4.if I am running a thread in java using run() if I call a method from inside the run() does this still running as a thread or it is not allowed?
1) Only if thread are daemons, application will not wait to close even if they are running.
Example: comment or not the setDaemon(true)
public class Test {
public static void main(final String[] args) {
new Launcher(parent).start();
}
public static class Launcher extends Thread {
public Launcher(final String name) {
this.setName(name);
}
#Override
public void run() {
System.err.println(getName() + is starting);
for (int i = 0; i < 10; i++) {
new Waiter(child + i).start();
}
try {
Thread.sleep(1000);
System.err.println(getName() + is no more sleeping);
} catch (final InterruptedException e) {
e.printStackTrace();
}
System.err.println(getName() + is stopping);
}
}
public static class Waiter extends Thread {
public Waiter(final String name) {
super(name);
super.setDaemon(true);
}
#Override
public void run() {
System.err.println(getName() + is starting);
try {
Thread.sleep(12000);
System.err.println(getName() + is no more sleeping);
} catch (final InterruptedException e) {
e.printStackTrace();
}
}
}
}
2) To force the stop, you can use different approach, different patterns. Sorry to not have THE solution. You can take a look at : http://docs.oracle.com/javase/7/docs/api/java/lang/ThreadGroup.html
3) Yeah, it's the goal of synchronized.
4) It depends what you do but basically, calling a method do not launch another thread, except if the methods does it.
if I have a class that runs a number of threads when one thread reaches to exit(1) command line will it exit the thread or the whole application including the other threads?
A call to System.exit(1) will terminate the calling thread and all other threads. It is the most brutal way of ending a Java program, namely completely shutting down the JVM, and should rarely be used at all.
how can I make one thread notify all other threads that run from the same class to stop?
Not at all. If you have references to the other Thread objects, you can call Thread#interrupt(), but whether or not the other threads check their interrupted status or reach a place where they may throw an InterruptedException is left to them.
does using synchronized make only one thread ,regardless his source in the code, to do this part of code?
Intuitively yes. However, when there is a wait() in this block, then the corresponding lock (that is, the object that was synchronized on) will be released and can be acquired by other threads.
if I am running a thread in java using run() if I call a method from inside the run() does this still running as a thread or it is not allowed?
When a thread calls a method, then the same thread also executes this method (silently wondering how else it should be...)
I have two tasks that should be run together.
The first task to save the data to the database. And the second task of recording video.
Currently I use a Thread for each task, and run it simultaneously.
...
Thread insertDb = new Thread(new Runnable() {
#Override
public void run() {
// Insert to Database
setDataMediaVisit(thumbStr);
insertVisitRecord();
}
});
Thread capture = new Thread(new Runnable() {
#Override
public void run() {
if (getGraph().getState() == DSCapture.PREVIEW) {
getGraph().setCaptureFile("data/"+ CaptureController.getNoMr() +"/videos/"+videoStr, DSFilterInfo.filterInfoForProfile(new File("profiles/demo_profile800x570_WM8_VBR_100.prx")), DSFilterInfo.doNotRender(), true);
getGraph().record();
}
setData(CaptureController.getNoMr());
}
});
insertDb.start();
capture.start();
...
Is the above code thread safe?
I want to use EDT, but i know EDT for Java Swing Component. CMIIW
Thank you.
THread safe is just an issue, when do you want use object that are running in specific thread with another thread. It's not clear here that you are using the share object in this 2 thread or not! But, if you wanna use some share object or you want to read and write from file or specific butter, you can use lock object like this:
final Object lock = new Object();
// In thread 1
// TODO: do some process in thread on
synchronized(lock) {
// TODO: Put the result in somewhere that thread2 want to read it
}
// In thread 2
synchronized(lock) {
// TODO: get the result from the place that you put in thread 1
}
// TODO: do some process on thread 2 on the data
You should always remember that you need to put smallest possible synchronized, because if the other thread reach to synchronized part, it will wait until thread 1 finish synchronized block and it can kill the performance of your code
Is there a way to check if a Thread object has had start called on it already?
I'm trying to so something like:
if(rt.isAlive() == true)
{
Log.v(TAG, "START RECORD");
rt.recording = true;
}
else
{
Log.v(TAG, "START THREAD/RECORD");
rt.start();
}
where it would start the thread if it's not already running.
Assuming that rt is a Thread, just check rt.isAlive().
Alternatively, just use a boolean flag and set it to true right before you start your thread.
I would actually prefer the boolean approach so there is no way that the main thread could start the other thread twice - there may be a short delay until your Thread is up and running, and if your main thread tries to start the thread twice in quick succession, it may get a "false" negative on rt.isAlive().
I've used this approach with success:
if ( mythread.getState() == Thead.State.NEW )
//then we have a brand new thread not started yet, lets start it
mythread.start();
else
//it is running already compensate
If you called start on it, and it is running, you will get an IllegalThreadStateException. Catching that is one way to know.
Another option is to extend Thread and add a boolean where you keep track of whether or not your Thread has been started. You can override the start method of Thread to check the boolean before calling up to super.start().
You should be very careful when using threads in Android though. Make sure you understand the lifecycle of the component that is starting it. Also, you should consider some of the helper classes like Handler and AsyncTask instead of directly spawning threads.
Call this method by passing a thread. It will check the thread is alive or not, every 500 milliseconds with start delay of 500 milliseconds (you can use your custom values). I use this method often.
void threadAliveChecker(final Thread thread) {
final Timer timer = new Timer();
timer.schedule(new TimerTask() {
#Override
public void run() {
if (!thread.isAlive()) {
// do your work after thread finish
runOnUiThread(new Runnable() {
#Override
public void run() {
// do the ui work here
}
});
timer.cancel();
}else {
// do work when thread is running like show progress bar
}
}
}, 500, 500); // first is delay, second is period
}
Example:
Thread thread = new Thread(myRunnable);
thread.start();
threadIsAliveChecker(thread);
This method will let us know when the thread is finished doing its work.