1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67
| public static void longRunningTask(ScheduledExecutorService scheduledExecutorService, long timeout) throws InterruptedException {
Thread thread = Thread.currentThread();
AtomicBoolean done = new AtomicBoolean(false);
scheduledExecutorService.schedule(new Runnable() { @Override public void run() { if (!done.get()) { done.set(true); thread.interrupt(); } } }, timeout, TimeUnit.MILLISECONDS);
// 模拟耗时工作 Thread.sleep(1000); }
public static void realInterruptTaskDemo() throws InterruptedException {
ScheduledExecutorService scheduledExecutorService = Executors.newScheduledThreadPool(1);
BlockingQueue<Runnable> workingQueue = new LinkedBlockingQueue<>(Integer.MAX_VALUE);
ThreadPoolExecutor executor = new ThreadPoolExecutor(2, 10, 60, TimeUnit.MILLISECONDS, workingQueue);
long start = System.currentTimeMillis();
CompletableFuture<Integer> future = CompletableFuture.supplyAsync(() -> { try { longRunningTask(scheduledExecutorService, 800); logger.info("[realInterruptTaskDemo.longRunningTask] finished"); return 1; } catch (InterruptedException e) { logger.info("[realInterruptTaskDemo.longRunningTask] canceled: {}", e.getMessage()); } return null; }, executor);
logger.warn("[realInterruptTaskDemo] active thread count: {}", executor.getActiveCount());
try { future.join(); } catch (CompletionException e) { logger.warn("[realInterruptTaskDemo] CompletionException: {}", e.getMessage()); } catch (CancellationException e) { logger.warn("[realInterruptTaskDemo] CancellationException: {}", e.getMessage()); }
logger.warn("[realInterruptTaskDemo] task is still running after join active thread count: {}, consumes: {}", executor.getActiveCount(), System.currentTimeMillis() - start);
if (future.isCompletedExceptionally()) { logger.warn("[realInterruptTaskDemo] future is error"); }
scheduledExecutorService.shutdown(); executor.shutdown(); }
// output 2024-07-26 11:59:50 WARN ConcurrentScoreDemo:281 - [realInterruptTaskDemo] active thread count: 1 2024-07-26 11:59:51 INFO ConcurrentScoreDemo:276 - [realInterruptTaskDemo.longRunningTask] canceled: sleep interrupted 2024-07-26 11:59:51 WARN ConcurrentScoreDemo:291 - [realInterruptTaskDemo] task is still running after join active thread count: 0, consumes: 803
|