新聞中心
這里有您想知道的互聯(lián)網(wǎng)營銷解決方案
控制Java線程超時(shí)后中止的方案
這里使用JDK5+的java.util.concurrent包下的API實(shí)現(xiàn),采用這種方式是相對比較安全的。

實(shí)現(xiàn)效果:
啟動一個(gè)任務(wù),然后等待任務(wù)的計(jì)算結(jié)果同時(shí)設(shè)定一個(gè)超時(shí)時(shí)間,如果等待時(shí)間超出預(yù)設(shè)定的超時(shí)時(shí)間,則中止任務(wù)。
代碼實(shí)現(xiàn):
- import java.util.concurrent.Callable;
- import java.util.concurrent.ExecutionException;
- import java.util.concurrent.ExecutorService;
- import java.util.concurrent.Executors;
- import java.util.concurrent.Future;
- import java.util.concurrent.TimeUnit;
- import java.util.concurrent.TimeoutException;
- /**
- * 啟動一個(gè)任務(wù),然后等待任務(wù)的計(jì)算結(jié)果,如果等待時(shí)間超出預(yù)設(shè)定的超時(shí)時(shí)間,則中止任務(wù)。
- *
- * @author Chen Feng
- */
- public class TaskTimeoutDemo {
- public static void main(String[] args) {
- System.out.println("Start ...");
- ExecutorService exec = Executors.newCachedThreadPool();
- testTask(exec, 15); // 任務(wù)成功結(jié)束后等待計(jì)算結(jié)果,不需要等到15秒
- testTask(exec, 5); // 只等待5秒,任務(wù)還沒結(jié)束,所以將任務(wù)中止
- exec.shutdown();
- System.out.println("End!");
- }
- public static void testTask(ExecutorService exec, int timeout) {
- MyTask task = new MyTask();
- Future
future = exec.submit(task); - Boolean taskResult = null;
- String failReason = null;
- try {
- // 等待計(jì)算結(jié)果,最長等待timeout秒,timeout秒后中止任務(wù)
- taskResult = future.get(timeout, TimeUnit.SECONDS);
- } catch (InterruptedException e) {
- failReason = "主線程在等待計(jì)算結(jié)果時(shí)被中斷!";
- } catch (ExecutionException e) {
- failReason = "主線程等待計(jì)算結(jié)果,但計(jì)算拋出異常!";
- } catch (TimeoutException e) {
- failReason = "主線程等待計(jì)算結(jié)果超時(shí),因此中斷任務(wù)線程!";
- exec.shutdownNow();
- }
- System.out.println("\ntaskResult : " + taskResult);
- System.out.println("failReason : " + failReason);
- }
- }
- class MyTask implements Callable
{ - @Override
- public Boolean call() throws Exception {
- // 總計(jì)耗時(shí)約10秒
- for (int i = 0; i < 100L; i++) {
- Thread.sleep(100); // 睡眠0.1秒
- System.out.print('-');
- }
- return Boolean.TRUE;
- }
- }
運(yùn)行結(jié)果:
- Start ...
- ----------------------------------------------------------------------------------------------------
- taskResult : true
- failReason : null
- ---------------------------------------------
- taskResult : null
- failReason : 主線程等待計(jì)算結(jié)果超時(shí),因此中斷任務(wù)線程!
- End!
網(wǎng)站欄目:控制Java線程超時(shí)后中止的方案
鏈接URL:http://www.dlmjj.cn/article/cdjsgpg.html


咨詢
建站咨詢
