Runtime.getRuntime().exec(command)的阻塞问题
2011-04-07 21:24
701 查看
使用 Runtime.getRuntime().exec(command)可以操作命令,如,打开某个软件,对某个文件进行转换等,它返回一个进程对象Process。对命令进行操作,操作成功与否,对我们的应用很重要。单纯的使用Process,可能会出现命令的执行一直处于阻塞的状态,后面的程序无法进行,(比如,我需要将word文件转换为flash文件,当出现意外word文件不合法,这个时候转换就不能成功,一直处于阻塞状态),我想到的解决方案是使用超时控制,程序执行超过我们约定的时间后,执行另一操作(资源回收等)
java 的java.util.concurrent包很值得看下
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; } }
相关文章推荐
- Runtime.getRuntime().exec()进程阻塞问题
- Runtime.getRuntime().exec执行阻塞问题解决
- Android通过Runtime.getRuntime().exec实现Ping和Traceroute命令时readLine阻塞问题解决
- Android通过Runtime.getRuntime().exec实现Ping和Traceroute命令时readLine阻塞问题解决
- Runtime.getRuntime().exec() 输出流阻塞问题
- java调用命令行Runtime.getRuntime().exec()函数碰到的阻塞问题
- java调用命令行Runtime.getRuntime().exec()阻塞问题
- Runtime.getRuntime().exec()执行阻塞问题解决
- Runtime.getRuntime().exec()进程阻塞问题
- Runtime.getRuntime().exec执行阻塞问题解决
- Runtime.getRuntime().exec执行阻塞问题解决
- Eclipse下使用Runtime.getRuntime().exec启动java程序的问题
- RunTime.getRuntime().exec()运行脚本命令介绍和阻塞
- Runtime.getRuntime().exec() 输出流阻塞的解决方法
- Runtime.getRuntime().exec();里面产生停滞(阻塞,blocking)
- Java Process中waitFor()的问题(使用Runtime.getRuntime().exec(...)时)
- 在runtime.getruntime().exec调用程序时路径的问题的解决方案列表
- Runtime.getRuntime().exec()出现阻塞,导致后续程序无法运行!
- Runtime.getRuntime().exec() 输出流阻塞的解决方法
- Runtime.getRuntime().exec中命令含有括号问题