标签:产生 抛出异常 row for public 练习 his except runnable
使用线程池方式—Callable接口 Callable接口:与Runnable接口功能相似,用来指定线程的任务。其中的call()方法,用来返回线程任务执行完毕后的结果,call方法可抛出异常。 ExecutorService:线程池类 <T> Future<T> submit(Callable<T> task):获取线程池中的某一个线程对象,并执行线程中的call()方法 Future接口:用来记录线程任务执行完毕后产生的结果。线程池创建与使用 使用线程池中线程对象的步骤: 创建线程池对象 创建Callable接口子类对象 提交Callable接口子类对象 关闭线程池 import java.util.concurrent.Callable; public class MyCallable implements Callable<String>{ public String call() throws Exception { return "abc"; } } import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class Test1 { public static void main(String[] args) throws InterruptedException, ExecutionException { //1.先从线程池工厂中获取线程池对象 ExecutorService es=Executors.newFixedThreadPool(2); //2.执行线程任务获取call方法执行后的返回值 Future<String> str=es.submit(new MyCallable()); //3.从Future对象中获取返回值 String s=str.get(); System.out.println(s);//abc //销毁线程池 es.shutdown(); } } 线程池练习:返回两个数相加的结果 import java.util.concurrent.Callable; public class CallSum implements Callable<Integer>{ private int num; public CallSum(){} public CallSum(int num){ this.num=num; } public Integer call() throws Exception { int sum=0; for(int i=1;i<num;i++){ sum+=i; } return sum; } } import java.util.concurrent.ExecutionException; import java.util.concurrent.ExecutorService; import java.util.concurrent.Executors; import java.util.concurrent.Future; public class Demo03 { //用线程实现计算 //由两个线程分别计算1-100的和 1-200的和 public static void main(String[] args) throws InterruptedException, ExecutionException { ExecutorService es=Executors.newFixedThreadPool(2); Future<Integer> f=es.submit(new CallSum(100)); System.out.println(f.get()); Future<Integer> f1=es.submit(new CallSum(200)); System.out.println(f1.get()); es.shutdown(); } }
标签:产生 抛出异常 row for public 练习 his except runnable
原文地址:https://www.cnblogs.com/zhaotao11/p/10250441.html