How do you kill a Thread in Java?

前端 未结 16 2039
天命终不由人
天命终不由人 2020-11-21 05:54

How do you kill a java.lang.Thread in Java?

16条回答
  •  渐次进展
    2020-11-21 06:28

    One way is by setting a class variable and using it as a sentinel.

    Class Outer {
        public static volatile flag = true;
    
        Outer() {
            new Test().start();
        }
        class Test extends Thread {
    
            public void run() {
                while (Outer.flag) {
                    //do stuff here
                }
            }
        }
    
    }
    

    Set an external class variable, i.e. flag = true in the above example. Set it to false to 'kill' the thread.

提交回复
热议问题