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 "線程執(zhí)行完成"; } }; 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(); |