After Starting the thread object
thread1.start();
thread2.start();
i need to wait for the finalization of both threads using the join() method(the most common way).
Like this.
try {
thread1.join();
thread2.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
All the tutorial i see uses some inbuilt method for finalization of threads.
Is there a way to wait for thread finalization without using any inbuilt method like join or executor ?
Every Thread has a state. NEW , RUNNABLE , BLOCKED , WAITING , TIMED_WAITING , or TERMINATED
TERMINATED is a state that you can look for every thread with thread.getState()
method, which is the state of thread once it finish execution
// 2 Thread Object
Thread threads[] = new Thread[2];
// store Thread Statuses
Thread.State status[] = new Thread.State[2];
Since All Thread have state. Before starting thread store their state
for (int i = 0; i < 2; i++) {
status[i] = threads[i].getState();
}
Once you start the thread The finished Thread has a state of Terminated, you can use it to and write your own check for finalization
// custom way for finalization of the threads
boolean finish = false; // initially all non finised
while(!finish) {
for (int i = 0; i < 2; i++) {
if (threads[i].getState() != status[i]) {
status[i] = threads[i].getState();
}
}
finish = true;
for (int i = 0; i < 2; i++) {
finish = finish && (threads[i].getState() ==
State.TERMINATED);
}
}