Intellipaat Back

Explore Courses Blog Tutorials Interview Questions
0 votes
2 views
in Java by (5.3k points)

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

1 Answer

0 votes
by (119k points)

You can kill a thread 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.

If you want to learn Java, you can enroll in this Java Training course by Intellipaat.

Related questions

0 votes
1 answer
0 votes
1 answer
asked Jan 5, 2021 in Linux by blackindya (18.4k points)
0 votes
1 answer
0 votes
1 answer
asked Jul 10, 2019 in Java by alan99 (830 points)

31k questions

32.8k answers

501 comments

693 users

Browse Categories

...