当执行一个耗时的操作,又不想影响已有的功能,我们可以做超时处理,当某个业务逻辑超过特定的时间时我们主动放弃断续执行下面的逻辑。
简单的代码实现
参考代码如下:
package easyfind.test; import java.util.concurrent.Callable; import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.FutureTask; import java.util.concurrent.TimeUnit; import java.util.concurrent.TimeoutException; /** * @author tank * @email kaixiong.tan@qq.com * @date:2015年7月30日 上午11:19:20 * @description: * @version :0.1 */ public class TestThreadTimeOut { public static void main(String[] args) { TestThreadTimeOut.Task task = new TestThreadTimeOut().new Task(); FutureTask<String> futureTask = new FutureTask<String>(task); //ExecutorService executor = Executors.newCachedThreadPool(); //executor.submit(futureTask); //executor.shutdown(); Thread thread = new Thread(futureTask); thread.start(); String result=null; try { result = futureTask.get(5, TimeUnit.SECONDS);//设置超时时间 } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (ExecutionException e) { // TODO Auto-generated catch block e.printStackTrace(); } catch (TimeoutException e) { // TODO Auto-generated catch block e.printStackTrace(); System.out.println("超时了"); } System.out.println(result); System.out.println("结束"); } class Task implements Callable<String> { @Override public String call() throws Exception { System.out.println("子线程请求中"); Thread.sleep(3000);//这里做耗时的处理业务逻辑 return "test"; } } }