문제

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.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top