The rp.num == 1 check should happen exactly at the point where rp.num is exactly one, which is unlikely.
In your main method, you start a thread that increments num every 200 ms. Subsequently, you check whether there is num == 1 , but when exactly this code is executed depends on many factors that you cannot control (OS planning, etc.). It can be after 10 ms (where the value will be 1), but it can also be after 300 ms (when the value is already 2). Also, when a thread is exactly running, it is not sure. Therefore, it is also possible that your thread starts only after the test. You can easily check this by replacing the check if(rp.num == 1) {rp.stop()}; to the simple print statement System.out.println(rp.num) . If you additionally wait some time before printing, you can get a better idea of ββwhat I'm talking about.
Suppose you want to stop runnable from the outside, I suggest using something like an observer pattern :
class MyRunnable implements Runnable { private final MyListener l; private volatile boolean exit; int num; public MyRunnable(MyListener l) { this.l = l; exit = false; } @Override public void run() { while(!exit) { System.out.println(t.currentThread().getName()+": "+num); l.check(num++); try { t.sleep(200); } catch(InterruptedException e) {} } } public void stop() { exit = true; } } class MyListener { private final threshold; public MyListener(int x) { this.threshold = x; } public void check(MyRunnable r, int num) { if (num >= threshold) r.stop(); } }
and your main method will look something like this:
public static void main(String[] args) { MyListener l = new MyListener(1); Runnable r = new MyRunnable(l); new Thread(r).start(); }
source share