fix:解决threadutil中中断异常处理丢失中断信息的问题,解决ConcurrencyTester资源未释放的问题

This commit is contained in:
孔纲 2025-06-05 10:20:18 +08:00
parent 04f9784d08
commit 4cf41c444f

View File

@ -1,7 +1,9 @@
package cn.hutool.core.thread; package cn.hutool.core.thread;
import cn.hutool.core.io.IORuntimeException;
import cn.hutool.core.util.RuntimeUtil; import cn.hutool.core.util.RuntimeUtil;
import java.io.IOException;
import java.lang.Thread.UncaughtExceptionHandler; import java.lang.Thread.UncaughtExceptionHandler;
import java.util.concurrent.Callable; import java.util.concurrent.Callable;
import java.util.concurrent.CompletionService; import java.util.concurrent.CompletionService;
@ -322,6 +324,8 @@ public class ThreadUtil {
try { try {
timeUnit.sleep(timeout.longValue()); timeUnit.sleep(timeout.longValue());
} catch (InterruptedException e) { } catch (InterruptedException e) {
// 重新标记线程为中断状态恢复中断信息让后续代码能感知到线程曾被中断过
Thread.currentThread().interrupt();
return false; return false;
} }
return true; return true;
@ -352,6 +356,8 @@ public class ThreadUtil {
try { try {
Thread.sleep(millis); Thread.sleep(millis);
} catch (InterruptedException e) { } catch (InterruptedException e) {
// 重新标记线程为中断状态恢复中断信息让后续代码能感知到线程曾被中断过
Thread.currentThread().interrupt();
return false; return false;
} }
} }
@ -506,7 +512,8 @@ public class ThreadUtil {
thread.join(); thread.join();
dead = true; dead = true;
} catch (InterruptedException e) { } catch (InterruptedException e) {
// ignore // 重新标记线程为中断状态恢复中断信息让后续代码能感知到线程曾被中断过
Thread.currentThread().interrupt();
} }
} while (false == dead); } while (false == dead);
} }
@ -613,7 +620,8 @@ public class ThreadUtil {
try { try {
obj.wait(); obj.wait();
} catch (InterruptedException e) { } catch (InterruptedException e) {
// ignore // 重新标记线程为中断状态恢复中断信息让后续代码能感知到线程曾被中断过
Thread.currentThread().interrupt();
} }
} }
} }
@ -629,9 +637,12 @@ public class ThreadUtil {
* @return {@link ConcurrencyTester} * @return {@link ConcurrencyTester}
* @since 4.5.8 * @since 4.5.8
*/ */
@SuppressWarnings("resource")
public static ConcurrencyTester concurrencyTest(int threadSize, Runnable runnable) { public static ConcurrencyTester concurrencyTest(int threadSize, Runnable runnable) {
return (new ConcurrencyTester(threadSize)).test(runnable); try (ConcurrencyTester tester = new ConcurrencyTester(threadSize)) {
return tester.test(runnable);
} catch (IOException e) {
throw new IORuntimeException(e);
}
} }
/** /**