Runtime.getRuntime().exec(command)的阻塞问题

本文介绍了一种在Java中实现命令执行超时控制的方法,通过使用java.util.concurrent包下的工具类,实现对Runtime.getRuntime().exec(command)命令执行的超时控制,避免因命令长时间阻塞导致程序挂起。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

使用 Runtime.getRuntime().exec(command)可以操作命令,如,打开某个软件,对某个文件进行转换等,它返回一个进程对象Process。对命令进行操作,操作成功与否,对我们的应用很重要。单纯的使用Process,可能会出现命令的执行一直处于阻塞的状态,后面的程序无法进行,(比如,我需要将word文件转换为flash文件,当出现意外word文件不合法,这个时候转换就不能成功,一直处于阻塞状态),我想到的解决方案是使用超时控制,程序执行超过我们约定的时间后,执行另一操作(资源回收等)

java 的java.util.concurrent包很值得看下

@SuppressWarnings("unchecked") public static void main(String[] args) { // Runtime.getRuntime().exec(command); try { Callable<Object> task = new Task(); ExecutorService executorService = Executors.newSingleThreadExecutor();// 单线程executor // returns A list of Futures representing the tasks, // in the same sequential order as produced by the iterator for the // given task list, each of which has completed List<Future<Object>> futures = executorService.invokeAll(Arrays.asList(task), 2L, TimeUnit.SECONDS); executorService.shutdown(); Future<Object> future = futures.get(0); if (future.isCancelled()) { // 如果已经超时,在这里操作 System.out.println("this task is cancelled!"); } } catch (Exception e) { e.printStackTrace(); } } } // 任务 class Task implements Callable<Object> { public Object call() throws Exception { try { System.out.println("started..."); // 在这里执行具体的应用 Thread.sleep(2000); //Thread.sleep(4000); System.out.println("finished..."); } catch (InterruptedException e) { // 超时后的操作 System.out.println("terminated..."); } return null; } }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值