通过关闭线程底层资源关闭类似synchronized及IO阻塞的情况
public class IoBlocked implements Runnable { private InputStream in; public IoBlocked(InputStream in) { this.in = in; } @Override public void run() { // TODO Auto-generated method stub try { print("Wait for read()"); int value=in.read(); // print("in.read():"+value); } catch (IOException e) { // TODO Auto-generated catch block if (Thread.currentThread().isInterrupted()) { print("interrupted from block IO "); } else { throw new RuntimeException(e); } } } }
public class CloseResource { /** * 1.ExecutorService.shutdownNow(): 通过Thread.interrupt()试图停止所有正在执行的线程,并不再处理还在队列中等待的任务<br> * 2.ExecutorService.shutdown(): 不允许提交新任务,等待当前任务及队列中的任务全部执行完毕后退出 * 3.当关闭阻塞的线程时会抛出异常:注意 * @param args * @throws IOException * @throws InterruptedException */ public static void main(String[] args) throws IOException, InterruptedException { ExecutorService executorService = Executors.newCachedThreadPool(); ServerSocket socket = new ServerSocket(8080);// 建立一个监控8080端口的服务器... InputStream socketInput = new Socket("localhost", 8080).getInputStream(); executorService.execute(new IoBlocked(socketInput)); executorService.execute(new IoBlocked(System.in)); TimeUnit.MILLISECONDS.sleep(100); print("Shutting down all Resources"); executorService.shutdownNow(); TimeUnit.SECONDS.sleep(1); print("Closeing:" + socketInput.getClass().getName()); socketInput.close(); TimeUnit.SECONDS.sleep(1); print("Closeing:" + System.in.getClass().getName()); System.in.close(); } }
output:
Wait for read()
Wait for read()
Shutting down all Resources
Closeing:java.net.SocketInputStream
interrupted from block IO
Closeing:java.io.BufferedInputStream
说明两点
1.关闭Executor启动的单个线程可以通过submit获取Future对象然后调用cancel方式来中断某个特定的任务!但对于像sync,IO阻塞无效
2.有趣点:
executorService.shutdownNow()视乎发生在关闭socket的那个时刻;但没任何证据;只是通过输出而已
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· 单线程的Redis速度为什么快?