final ExecutorService exec = Executors.newFixedThreadPool(1); Callable call = new Callable() { public String call() throws Exception { // 放入耗时操作代码块 int cash = 300; String name = "张三"; System.out.println(name + "现在有" + cash + "元存款"); User u = new User(name, cash); String[] arr = { "线程A", "线程B", "线程C", "线程D", "线程E", "线程F", "线程G", "线程H", "线程I", "线程J" }; for (int i = 0; i < 10; i++) { MyThread th = new MyThread(arr[i], u, (int) (Math.random() * 1000 - 500)); th.start(); } //耗时代码块结束 Thread.sleep(1000 * 5); return "线程执行完成"; } }; try { Future future = exec.submit(call); String obj = future.get(1000 * 1, TimeUnit.MILLISECONDS); // 任务处理超时时间设为1 秒 System.out.println("任务成功返回:" + obj); } catch (TimeoutException ex) { System.out.println("处理超时啦...."); System.exit(0); } catch (Exception e) { System.out.println("处理失败."); e.printStackTrace(); } exec.shutdown(); // 关闭线程池 将耗时的代码块放入标注的地方后,即可满足要求。 System.out.println("处理失败."); e.printStackTrace(); System.out.println("处理失败."); e.printStackTrace(); |