老师,这是正常的情况吗?暂停后到输出剩余吨数的时候还在放水
package com.ethan.test; import java.util.concurrent.*; import java.util.concurrent.locks.Condition; import java.util.concurrent.locks.ReentrantLock; public class Test3_13 extends ThreadPoolExecutor { private final ReentrantLock lock = new ReentrantLock(); private final Condition unpause = lock.newCondition(); private boolean isPaused; public Test3_13(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue); } public Test3_13(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory); } public Test3_13(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, RejectedExecutionHandler handler) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, handler); } public Test3_13(int corePoolSize, int maximumPoolSize, long keepAliveTime, TimeUnit unit, BlockingQueue<Runnable> workQueue, ThreadFactory threadFactory, RejectedExecutionHandler handler) { super(corePoolSize, maximumPoolSize, keepAliveTime, unit, workQueue, threadFactory, handler); } @Override protected void beforeExecute(Thread t, Runnable r) { super.beforeExecute(t, r); lock.lock(); try{ while(isPaused){ unpause.await(); } }catch (InterruptedException e) { e.printStackTrace(); }finally { lock.unlock(); } } public void pause(){ lock.lock(); try{ isPaused = true; }finally { lock.unlock(); } } public void resume(){ lock.lock(); try{ isPaused = false; unpause.signalAll(); }finally { lock.unlock(); } } public static void main(String[] args) { Test3_13 test3_13 = new Test3_13(10,20,10l,TimeUnit.SECONDS,new LinkedBlockingQueue<>()); System.out.println("上班啦,水池放入1000吨水"); for (int i = 0; i < 10000; i++) { test3_13.execute(new RunTest()); } try { Thread.sleep(200); } catch (InterruptedException e) { e.printStackTrace(); } test3_13.pause(); System.out.println("暂停放水中。。。。。。。。"); System.out.println("中午啦,回家吃饭啦,水池被暂停了。还剩吨"+test3_13.getQueue().size()+"吨水"); } } class RunTest implements Runnable{ @Override public void run() { System.out.println("正在放水"); try { Thread.sleep(10); } catch (InterruptedException e) { System.out.println("================interrupt==========="); } } }
3
收起
正在回答 回答被采纳积分+1
1回答
恭喜解决一个难题,获得1积分~
来为老师/同学的回答评分吧
0 星