why my thread can't be stopped???
class Threadz {
class runP implements Runnable {
int num;
private volatile boolean exit = false;
Thread t;
public runP() {
t = new Thread(this, "T1");
t.start();
}
@Override
public void run() {
while(!exit) {
System.out.println(t.currentThread().getName()+": "+num);
num++;
try {
t.sleep(200);
} catch(InterruptedException e) {}
}
}
public void stop() {
exit = true;
}
}
public static void main(String[] a) {
runP rp = new Threadz().new runP();
if(rp.num == 1) {rp.stop();}
}
}
if i use rp.num == 0, the thread can be stopped immediately. But, why when i changed the rp.num == x (x is any number greater than 0) the thread cannot stop? please help me solve this thing... thanks for any helps.
Because this code is not executed in the run() method of the thread :
runP rp = new Threadz().new runP();
if (rp.num == 1) {
rp.stop();
}
It works with 0 as the default value of int is 0.
But it is not necessarily true in all executions of the application as the thread of runP
could run and incrementnum
before the check : if (rp.num == 0)
Move the stop condition in the run method of the runP thread :
@Override
public void run() {
while(!exit) {
System.out.println(t.currentThread().getName()+": "+num);
num++;
try {
t.sleep(200);
} catch(InterruptedException e) {}
if (rp.num == 1) {
exit = true;
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With