码上敲享录 > java高并发常见问题 > Callable接口结合线程池使用

Callable接口结合线程池使用

上一章章节目录下一章 2018-08-27已有3338人阅读 评论(0)

Callable结合线程池使用


解决方法:

1.Callable线程类

import java.util.concurrent.Callable;

public class CallableDemo implements Callable<String> {

private int begin;

private int end;

private int sum;

public CallableDemo(int begin, int end) {

super();

this.begin = begin;

this.end = end;

}


public String call() throws Exception {

for(int i=begin;i<=end;i++){

for(int j=begin;j<=end;j++){

sum+=j;

}

}

Thread.sleep(8000);

return begin+"-" +end+"的和:"+ sum;

}

}


2.测试,启动两个Callable线程

public static void main(String[] args) throws Exception {

CallableDemo callable = new CallableDemo(1,100000);

CallableDemo callable2 = new CallableDemo(1,100000);

ThreadPoolExecutor executor = new

ThreadPoolExecutor(4, 5, 5L,

TimeUnit.SECONDS, new LinkedBlockingDeque());

        System.out.println("main 1 " +System.currentTimeMillis());

Future<String> future =executor.submit(callable);

Future<String> future2 =executor.submit(callable2);

System.out.println("main 2 " +System.currentTimeMillis());

System.out.println(future.get());

System.out.println("main 3 " +System.currentTimeMillis());

System.out.println(future2.get());

System.out.println("main 4 " +System.currentTimeMillis());

}


本文链接:http://www.yayihouse.com/yayishuwu/chapter/1543


1

有建议,请留言!

  • *您的姓名:

  • *所在城市:

  • *您的联系电话:

    *您的QQ:

  • 咨询问题:

  • 提 交