final ExecutorService exec = Executors.newFixedThreadPool(1); Callable call = new Callable() { public String call() throws Exception { // 放入耗時(shí)操作代碼塊 int cash = 300; String name = "張三"; System.out.println(name + "現(xiàn)在有" + 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(); } //耗時(shí)代碼塊結(jié)束 Thread.sleep(1000 * 5); return "線程執(zhí)行完成"; } }; try { Future future = exec.submit(call); String obj = future.get(1000 * 1, TimeUnit.MILLISECONDS); // 任務(wù)處理超時(shí)時(shí)間設(shè)為1 秒 System.out.println("任務(wù)成功返回:" + obj); } catch (TimeoutException ex) { System.out.println("處理超時(shí)啦...."); System.exit(0); } catch (Exception e) { System.out.println("處理失敗."); e.printStackTrace(); } exec.shutdown(); // 關(guān)閉線程池 將耗時(shí)的代碼塊放入標(biāo)注的地方后,即可滿足要求。 System.out.println("處理失敗."); e.printStackTrace(); System.out.println("處理失敗."); e.printStackTrace(); |