I have to execute an x thread and let the y thread start only when x terminates regardless of the time it will take, and then execute z only when a and terminate. Anyone know what the best way to do this? Thank you in advance.
I have to execute an x thread and let the y thread start only when x terminates regardless of the time it will take, and then execute z only when a and terminate. Anyone know what the best way to do this? Thank you in advance.
It is unusual to find situations where one thread has to wait for another serially. However, these situations exist, so here it goes:
Use the method Thread.join()
. This is an instance method of class Thread
. This way, a call to t.join();
, where t
is an instance of Thread
, will cause the current thread ( Thread.currentThread()
) to wait for the end of the referenced thread ( t
).
Here's an example:
public class EsperaThreads {
public static void main(String[] args) {
Thread z = new Thread(new Runnable() {
@Override
public void run() {
System.out.println("Thread z");
}
});
Thread y = new Thread(new Runnable() {
@Override
public void run() {
try {
z.join();
System.out.println("Thread y");
} catch (InterruptedException e) {
System.out.println("Thread y foi interrompida enquanto esperava z");
}
}
});
Thread x = new Thread(new Runnable() {
@Override
public void run() {
try {
y.join();
System.out.println("Thread x");
} catch (InterruptedException e) {
System.out.println("Thread x foi interrompida enquanto esperava y");
}
}
});
x.start();
y.start();
// Se quiser, coloque um Thread.sleep aqui para perceber que x e y não saem na frente de z.
z.start();
}
}
Note that the join()
method can throw a InterruptedException
. This exception is thrown in a case such as when the y
thread is stopped at z.join()
and some other thread gives a y.interrupt()
, signaling that the y
thread should give up waiting. And because of that, in the catch
you do the treatment in the case of "another thread sent this from here to give up waiting". This is useful for signaling situations where you want the aborted action to be aborted or aborted.
The join()
method also has two other overloaded versions: join(int millis)
and join(int millis, int nanos)
. These versions wait for a maximum time before giving up and moving on. If you pass zero as a parameter, they will wait as long as necessary (or forever, if the expected thread never ends).