The code below is that I try to stop a thread I created without using stop(). However, The thread seems like it would executed once more after it be stopped. I wonder why this happened? Plus: If I change the iteration from 100 to 10, it works without any problems. Can anyone help me with this problem? Thanks in advance!
public class TerminateThread implements Runnable{
private boolean flag = true;
public TerminateThread(String name) {
this.name = name;
}
private String name;
public void run() {
int i = 0;
while(flag) {
System.out.println(name+"--->"+i++);
}
}
public void Terminate() {
this.flag = false;
}
public static void main(String[] args) {
TerminateThread tt = new TerminateThread("Thread");
new Thread(tt).start();
for (int i = 0; i <= 100; i++) {
if (i == 88) {
tt.Terminate();
System.out.println("Thread terminated!!!");
}
System.out.println("main--->" + i);
}
}
}