简体   繁体   中英

How to terminate a thread even if it has not finished running?

My program start a thread whether some objects is created.

Foo() {
   t = new Thread(this);
   t.start();
}

And I am running some while loop inside my threads.

while(bool){
   // do something
}

I have one thread controlling the value of the boolean bool. But how can I terminate some of them before my other thread change the boolean value? I think setting t = null doesn't work. Is there any way to garbage collect the thread before it stop running?

Change the loop to

while (bool && !Thread.interrupted()) {
    // do something
}

When you want to stop the thread, call

t.interrupt();

Good luck.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM