使用 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; } }