ExecutorService cachedThreadPool = Executors.newCachedThreadPool(); for (int i = 0; i < 300; i++) { final int index = i; Future<?> future = cachedThreadPool.submit(new Runnable() { public void run() { System.out.println(index); if (index == 5 || index==100 || index == 200) { try { Thread.sleep(1000 * 100000); } catch (InterruptedException e) { } } } }); try { //一秒如果不返回,直接放弃。 Object obj = future.get(1000 * 1, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { System.out.println(Thread.currentThread().getName()+" is Interrupted."); } catch (ExecutionException e) { e.printStackTrace(); } catch (TimeoutException e) { System.out.println(index+"这个线程超时啦,直接放弃处理..."); }finally { future.cancel(true); } } cachedThreadPool.shutdown(); System.out.println("All thread shutdown");
多线程批量异步执行
最新推荐文章于 2024-07-05 17:25:50 发布