I am learning Multithreading and Concurrency in Java on my own. Please help me understand this piece of code. I am creating a thread with a 'stop' boolean variable, the 'run' method loops continuously until the main thread sets the stop variable to true after sleeping for two seconds. However, I am observing this code runs in an infinite loop. What am I doing wrong here?
public class Driver {
public static void main(String[] args) {
ThreadWithStop threadWithStop = new ThreadWithStop();
Thread thread = new Thread(threadWithStop);
thread.start();
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
e.printStackTrace();
}
threadWithStop.stopThread();
}
}
class ThreadWithStop implements Runnable {
private boolean stop;
public ThreadWithStop() {
this.stop = false;
}
public void stopThread() {
this.stop = true;
}
public boolean shouldRun() {
return !this.stop;
}
@Override
public void run() {
long count = 0L;
while (shouldRun()) {
count++;
}
System.out.println(count+"Done!");
}
}
stopsolve the problem?