level 8
比如说我起了个线程池来分别处理事务,随便写了点伪代码哈。
List<Future<T>> resultList = new ArrayList<>();
taskLists.forEach(task->resultList.add(taskExecutor.submit(()->run(task))));
resultList.forEach(res->System.out.println(res.get(5,TimeUnit.SECONDS)));
然后重点来了,比如说我这个resList里面有20个future,然后所有任务都超时,是会阻塞20*5 100秒吗?
2019年07月23日 10点07分
1
level 8
下班回家写了个测试加上复习了一下源码,发现虽然.get是阻塞,但是不会影响下一个get继续执行。 此贴终结-----(果然贴吧只能水吗)
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.*;
public class test {
public static void main(String[] args){
long t1 = System.currentTimeMillis();
test();
System.out.println(System.currentTimeMillis()-t1);
}
private static void test(){
ExecutorService pool = Executors.newFixedThreadPool(10);
List<Future<String>> list= new ArrayList<>();
for(int i =0;i<10;i++){
list.add(pool.submit(()->{
try {
TimeUnit.SECONDS.sleep(5);
//System.out.println(Thread.currentThread().getName()+"---");
return Thread.currentThread().getName()+"---";
} catch (InterruptedException e) {
e.printStackTrace();
}finally {
return Thread.currentThread().getName()+"---";
}
}));
}
System.out.println(list);
list.forEach(a-> {
try {
System.out.println(a.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
});
}
}
附上demo,各位不想写notify和wait的,用Future和get方法很舒服哈。
2019年07月23日 12点07分
3
level 15
不会,你不get他也会运行,不然不就是同步的了吗。。。
2019年07月25日 00点07分
8