Consider this code :-
class A {
Thread t = new Thread() {
@Override
public void run() {
super.run();
// Tons of statements.... (Set 1)
if(/* We don't meet certain requirements for continuing */) {
// Exit and stop the thread and do not execute any following statements after the if block
}
// Tons of statements.... (Set 2)
}
};
public void run() {
t.start();
}
}
class B {
public static void main(String[] args) {
A obj = new A();
obj.run();
}
}
We start our program with main
of class B.
Say that main
in class B finishes all it's instructions while Thread t
is still executing it's statments in set 1.
Now, there are only two ways for the t
to stop. Either it reaches end of statement Set 2 (this will result in thread dying out), or the if
block stops the Thread t
.
I want to know how can such an if block be implemented ?
If i simply write join()
, then the Thread t
doesn't seem to execute furthur command but it stays ALIVE and does not dies out (What i have observed from my experiments).
And stop()
is depreciated. So what is the proper way to implement the necessary if
block. What should the body, so that if certain critera do not meet before continuti, we enter the if block and then the code ends the tread without executing any further instruction (below the if block) and then the Thread DIES immediately.
NOW, CLEARLY A SIMPLE & PROPER SOLUTION IS JUST TO PUT ALL THE SET2 INSTRUCTIONS IN else
BLOCK,
but i'd like to know if there is some other proper way to do this.
I am making a text based game and I create multiple instances of Class A
. For each instance of A, I have to make such checks at multiple places.
Putting all the further code in else
blocks will make the code too nested. Indentation looks bad and it feels like this is not the proper approach.
And it will also help me understand threads better. Starting threads is easy, but stopping them always takes a heavy toll on my brain.