Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Thread cannot stop

Tags:

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.

like image 558
Asker Avatar asked Jan 17 '17 14:01

Asker


1 Answers

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;
        }
    }
}
like image 196
davidxxx Avatar answered Oct 13 '22 19:10

davidxxx