在java编程中,有时候会需要及时获取线程的运行结果,本文就通过一个相关实例向大家介绍java利用future及时获取线程运行结果的方法,需要的朋友可以参考。
future接口是java标准api的一部分,在java.util.concurrent包中。future接口是java线程future模式的实现,可以来进行异步计算。
有了future就可以进行三段式的编程了,1.启动多线程任务2.处理其他事3.收集多线程任务结果。从而实现了非阻塞的任务调用。在途中遇到一个问题,那就是虽然能异步获取结果,但是future的结果需要通过isdone来判断是否有结果,或者使用get()函数来阻塞式获取执行结果。这样就不能实时跟踪其他线程的结果状态了,所以直接使用get还是要慎用,最好配合isdone来使用。
这里有一种更好的方式来实现对任意一个线程运行完成后的结果都能及时获取的办法:使用completionservice,它内部添加了阻塞队列,从而获取future中的值,然后根据返回值做对应的处理。一般future使用和completionservice使用的两个测试案例如下:
import java.util.arraylist;
import java.util.list;
import java.util.random;
import java.util.concurrent.callable;
import java.util.concurrent.executorservice;
import java.util.concurrent.executors;
import java.util.concurrent.future;
/**
* 多线程执行,异步获取结果
*
* @author i-clarechen
*
*/
public class asyncthread {
public static void main(string[] args) {
asyncthread t = new asyncthread();
list<future<string>> futurelist = new arraylist<future<string>>();
t.generate(3, futurelist);
t.dootherthings();
t.getresult(futurelist);
}
/**
* 生成指定数量的线程,都放入future数组
*
* @param threadnum
* @param flist
*/
public void generate(int threadnum, list<future<string>> flist) {
executorservice service = executors.newfixedthreadpool(threadnum);
for (int i = 0; i < threadnum; i++) {
future<string> f = service.submit(getjob(i));
flist.add(f);
}
service.shutdown();
}
/**
* other things
*/
public void dootherthings() {
try {
for (int i = 0; i < 3; i++) {
system.out.println("do thing no:" + i);
thread.sleep(1000 * (new random().nextint(10)));
}
} catch (interruptedexception e) {
e.printstacktrace();
}
}
/**
* 从future中获取线程结果,打印结果
*
* @param flist
*/
public void getresult(list<future<string>> flist) {
executorservice service = executors.newsinglethreadexecutor();
service.execute(getcollectjob(flist));
service.shutdown();
}
/**
* 生成指定序号的线程对象
*
* @param i
* @return
*/
public callable<string> getjob(final int i) {
final int time = new random().nextint(10);
return new callable<string>() {
@override
public string call() throws exception {
thread.sleep(1000 * time);
return "thread-" + i;
}
};
}
/**
* 生成结果收集线程对象
*
* @param flist
* @return
*/
public runnable getcollectjob(final list<future<string>> flist) {
return new runnable() {
public void run() {
for (future<string> future : flist) {
try {
while (true) {
if (future.isdone() && !future.iscancelled()) {
system.out.println("future:" + future
+ ",result:" + future.get());
break;
} else {
thread.sleep(1000);
}
}
} catch (exception e) {
e.printstacktrace();
}
}
}
};
}
}
运行结果打印和future放入列表时的顺序一致,为0,1,2:
do thing no:0
do thing no:1
do thing no:2
future:java.util.concurrent.futuretask@68e1ca74,result:thread-0
future:java.util.concurrent.futuretask@3fb2bb77,result:thread-1
future:java.util.concurrent.futuretask@6f31a24c,result:thread-2
下面是先执行完的线程先处理的方案:
import java.util.random;
import java.util.concurrent.blockingqueue;
import java.util.concurrent.callable;
import java.util.concurrent.completionservice;
import java.util.concurrent.executionexception;
import java.util.concurrent.executorcompletionservice;
import java.util.concurrent.executorservice;
import java.util.concurrent.executors;
import java.util.concurrent.future;
import java.util.concurrent.linkedblockingdeque;
public class testcallable {
public static void main(string[] args) {
try {
completionservicecount();
} catch (interruptedexception e) {
e.printstacktrace();
} catch (executionexception e) {
e.printstacktrace();
}
}
/**
* 使用completionservice收集callable结果
* @throws executionexception
* @throws interruptedexception
*/
public static void completionservicecount() throws interruptedexception, executionexception {
executorservice executorservice = executors.newcachedthreadpool();
completionservice<integer> completionservice = new executorcompletionservice<integer>(
executorservice);
int threadnum = 5;
for (int i = 0; i < threadnum; i++) {
completionservice.submit(gettask(i));
}
int sum = 0;
int temp = 0;
for(int i=0;i<threadnum;i++){
temp = completionservice.take().get();
sum += temp;
system.out.print(temp + "\t");
}
system.out.println("completionservice all is : " + sum);
executorservice.shutdown();
}
public static callable<integer> gettask(final int no) {
final random rand = new random();
callable<integer> task = new callable<integer>() {
@override
public integer call() throws exception {
int time = rand.nextint(100)*100;
system.out.println("thead:"+no+" time is:"+time);
thread.sleep(time);
return no;
}
};
return task;
}
}
运行结果为最先结束的线程结果先被处理:
thead:0 time is:4200
thead:1 time is:6900
thead:2 time is:2900
thead:3 time is:9000
thead:4 time is:7100
0 1 4 3 completionservice all is : 10
总结
以上就是java如何使用future及时获取多线程运行结果的实例分析的详细内容。