public class ThreadDemo implements Runnable { @Override public void run() { // 轮询中断状态 while (Thread.currentThread().isInterrupted()) { doSomething(); } } }
public class ThreadDemo implements Runnable { @Override public void run() { while (!Thread.currentThread().isInterrupted()) { doFirstPartOfIncrement(); try { Thread.sleep(1000); } catch (InterruptedException e) { // 抛出了InterruptException,此时会清除当前线程的中断状态,需要重新设置中断状态,保证线程正常终止 Thread.currentThread().interrupt(); } } } }
public class ThreadDemo implements Runnable { // 状态变量 private volatile boolean stop = false; public void stop() { stop = true; } @Override public void run() { // 轮询状态变量 while (!stop) { doSomething(); } } }
This method is inherently unsafe. Stopping a thread with Thread.stop causes it to unlock all of the monitors that it has locked (as a natural consequence of the unchecked ThreadDeath exception propagating up the stack). If any of the objects previously protected by these monitors were in an inconsistent state, the damaged objects become visible to other threads, potentially resulting in arbitrary behavior.
会将此线程获取的Monitor对象(也就是常说的通过synchronized获取的锁)释放。比如一个线程负责维护一个对象Product中的两个变量saleCount和StockCount处于saleCount <= stockCount状态,当某个时刻saleCount > stockCount,同时此线程被stop()强制停止,会导致逻辑错误。
如对本文有疑问, 点击进行留言回复!!
MyBatis——动态SQL语句——if标签和where标签复合使用
解决Server returns invalid timezone. Go to ‘Advanced‘ tab and set ‘serverTimezone‘ prope后还会报500错的方法
网友评论