在Volatile修正案例中,while循环似乎不需要判断isInterrupted()也可以停止运行,那么判断isInterrupted是否是没有必要的? 即便是加了isInterrupted()判断,异常却是由storage.put(num);抛出而并不是isInterrupted()方法跳过了while。而storage.put(num);发生阻塞不是在while中吗?似乎这种循环阻塞的情况不是不需要在while处判断isInterrupted()吗??
下边贴出我的 Volatile修正demo中生产者的run方法 参考。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | // Volatile修正demo中生产者的run方法 @Override public void run() { int num = 0 ; try { // 似乎并不需要判断(响应)停止期望,本线程也可以异常停止. // !Thread.currentThread().isInterrupted() while (num <= 10000 ) { if (num % 100 == 0 ) { System.out.println( "100的倍数放入仓库 num = " + num); storage.put(num); // InterruptedException } num++; } } catch (InterruptedException e) { e.printStackTrace(); } finally { System.out.println( "生产者停止运行" ); } } |