The immediate answer to your question is that your flag is static so all instances of your Thread subclass see the same flag; making it instance-scope instead of static will mean the individual thread objects can be stopped separately. Also making the flag volatile will mean that the updates to the flag will be visible to the Thread subclass instances. Without volatile
the flag checks can be optimized away by the JVM.
But using your own flag to cancel the thread isn't a good idea. There's a perfectly good flag already made for you and baked into the Thread class. In fact, it's better than anything you could come up with, because your thread can't stop sleeping or waiting to check your own flag, so once you set it the thread may take a while to respond. But if you use the interruption facility then the thread can check its own interrupted flag and stop sleeping or waiting right away.
Here's your example reworked to use interruption. In your example the output doesn't distinguish between Thread1 and Thread2, I added a name to help with that. Also I added a sleep to the thread (in order to cut down on the amount of stuff written to the console as well as to demonstrate interrupting a sleeping thread), and had the example cancel the second thread as well, after waiting long enough to make clear which thread was canceled first.
public class Thread1 extends Thread {
public Thread1(String name) {
super(name);
}
public void run() {
try {
while (!Thread.currentThread().isInterrupted()) {
System.out.println(getName());
//BUSINESS LOGIC//
Thread.sleep(1000L);
}
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
System.out.println("thread " + getName() + " woke up");
}
System.out.println("thread " + getName() + " finished");
}
public static void main(String[] args) throws Exception {
Thread1 t1 = new Thread1("t1");
t1.start();
Thread1 t2 = new Thread1("t2");
t2.start();
Thread.sleep(5000L);
t1.interrupt(); // cancel the first thread
Thread.sleep(5000L);
t2.interrupt(); // cancel the second thread
}
}
The output looks like:
t1
t2
t1
t2
t2
t1
t2
t1
t2
t1
thread t1 woke up
thread t1 finished
t2
t2
t2
t2
t2
thread t2 woke up
thread t2 finished
I have another example of thread interruption with more details here.