In the following code why is it that calling the shutDown() method using a new instance doesn't stop the while loop but when I call the shutDown() method using the existing instance of Processor class then the loop terminates?
It is my understanding ( from this link difference between processes and threads) that threads are subsets of processes and all threads within a process share the same heap, memory etc. Now if the 'private boolean running' variable is shared between all threads(since it is a class variable) then why doesn't the new Processor instance new Processor().shutDown(), change said variable to false?
import java.util.Scanner;
class Processor extends Thread {
private boolean running = true;
public void run() {
while(running) {
System.out.println(" hello ppl");
try {
Thread.sleep(50);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
public void shutDown() {
running = false;
}
}
public class App1 {
public static void main(String[] args) {
Processor p1 = new Processor();
p1.start();
System.out.println("press enter to stop");
Scanner scanner = new Scanner(System.in);
scanner.nextLine();
p1.shutDown(); // THIS WORKS
//new Processor().shutDown(); // THIS DOESNT!!
}
}
private boolean runningvariable – it is a class instance field (each instance ofProcessorhas its own) and not a class field (all instance share the same one). To use a class field as you intended, you have to declare itstatic. However, you must synchronize the access to the shared space. - interDist