- 线程类:
- /**
- * 类名称:CallableTest.java
- * 类描述:
- * 作 者:why
- * 时 间:2016年11月7日
- */
- public class CallableTest implements Callable<String> {
- //接收传来的值
- private String str;
- public CallableTest(String str){
- super();
- this.str = str;
- }
- @Override
- public String call() throws Exception {
- //要执行的耗时操作,为了体验效果,没调用一次,休眠1000ms
- Thread.sleep(1000);
- return str;
- }
- }
- 调用类:
- /**
- * 类名称:RunTest.java
- * 类描述:
- * 作 者:why
- * 时 间:2016年11月7日
- */
- public class RunTest {
- public static void main(String[] args) {
- //创建线程池
- ExecutorService ex=Executors.newCachedThreadPool();
- List<CallableTest> taskList = new ArrayList<CallableTest>();
- long now=System.currentTimeMillis();
- taskList.add(new CallableTest("1"));
- taskList.add(new CallableTest("2"));
- taskList.add(new CallableTest("3"));
- taskList.add(new CallableTest("4"));
- try {
- //调用线程,并且接收线程返回的结果
- List<Future<String>> as =ex.invokeAll(taskList);
- for(Future<String> f:as){
- //打印返回结果
- System.out.println(f.get());
- }
- } catch (InterruptedException e) {
- e.printStackTrace();
- } catch (ExecutionException e) {
- e.printStackTrace();
- }
- System.out.println((System.currentTimeMillis()-now));
- }
- }
- 输出结果:
- 1
- 2
- 3
- 4
- 1003(耗时)
- 正常情况下,执行4次所用时间应给是4000ms,而并发调用,用时1003ms。
java 线程 callable
最新推荐文章于 2025-08-19 18:46:01 发布