使用Future停止超时任务



今天学了下多线程中超时任务的处理,这里和大家分享下,遇到了点问题没能解决,留下来希望大家帮我解疑啊。

在JAVA中停止线程的方法有多种,服务器空间,有一种是结合ExecutorService和Future的使用,停止在线程池中超时的任务。这种情况下处理的都是比较耗时的操作,比如请求资源,数据库查询等,当超过一定时间没有返回结果,就结束线程,虚拟主机,提高响应速度。

具体步骤如下:

下面是一个下载大文件的程序,网站空间,如果下载任务超时将关闭任务。(DownloadTask.java: 下载任务)

1 class DownloadTask implements Runnable { 2private String filename; Throwable exception;isStop = false;setStop(boolean isStop) { 9this.isStop = isStop;10 } DownloadTask(String filename) {13this.filename = filename;14 }* 下载大数据18 * filename FileNotFoundException21 *, IOExceptiondownload() throws FileNotFoundException, IOException {24File file = new File(filename);25File saveFile = null;26String[] names = filename.split(“/”);27String saveName = names[names.length – 1];28saveFile = new File(“tmp/” + saveName);29InputStream input = new FileInputStream(file);30OutputStream output = new FileOutputStream(saveFile);len = 0;[1024];35while (-1 != (len = input.read(buffer, 0, buffer.length))) {36if(isStop)37break;38output.write(buffer, 0, len);39 }40 41 input.close();42 output.close();43 }throwException() throws FileNotFoundException, IOException {46if (exception instanceof FileNotFoundException)47throw (FileNotFoundException) exception;48if (exception instanceof IOException)49throw (IOException) exception;50 }51 52 @Override run() {54try {55 download();56} catch (FileNotFoundException e) {57exception = e;58} catch (IOException e) {59exception = e;60 }61 }62 }夫妇一条心,泥土变黄金。

使用Future停止超时任务

相关文章:

你感兴趣的文章:

标签云: