最近开始做java项目,涉及多线程问题,有一事不太明白
网上说不推荐用thread.stop()
应该用thread.interrupt()但是实际中发现如果thread没有用到sleep(),是不能被catach到InterruptException的那我如果在thread中就是个while(true)的循环,而且里面没有用到Thread.sleep()但是我又想随时中断thread,而不是一个循环做完后通过一个while(stopped)来控制应该怎么做呢?
网上说不推荐用thread.stop()
应该用thread.interrupt()但是实际中发现如果thread没有用到sleep(),是不能被catach到InterruptException的那我如果在thread中就是个while(true)的循环,而且里面没有用到Thread.sleep()但是我又想随时中断thread,而不是一个循环做完后通过一个while(stopped)来控制应该怎么做呢?
if(Thread.interrupted())
break;
//do sth here
...
...
}
//do sth
}
//当要停止线程时,将
isTrue = false;
所以使用while(stopped),设置stopped后,如果正在处理数据,在处理完后会退出当然,如果线程正在sleep,应该立即唤醒