【我的Java笔记】多线程_多线程实现的第三种方式(线程池)

来源:互联网 发布:淘宝活动利益点怎么写 编辑:程序博客网 时间:2024/06/05 09:42

Executors(工厂类)

方法:public static ExecutorService newFixedThreadPool(int nThreads)指定在线程池中多少条线程
注:此方法返回的是ExecutorService对象,该对象表示一个线程池,可以执行Runnable对象或者Callable对象代表的线程


ExecutorService(接口)


方法:(此方法相当于Thread中的start() 方法
(1)Future<?> submit(Runnable task)提交任务
(2)<T> Future<T> submit(Callable<T> task) 该返回值表示异步计算的结果

关闭线程池方法:
(1)void shutdown ()


Callable(接口)

方法:(1)V call() 
注:此方法有返回值


Future接口(用于计算)

方法:
(1)V get() 等待计算完成,然后获取其结果

注:获取异步计算的结果,返回值类型与Callable接口泛型相同





*多线程实现的第三种方式操作步骤:

(1)自定义一个类实现Callable接口
(2)自定义类中重写Callable接口中的 call() 方法
(3)在主线程中创建ExecutorService对象,并调用submit() 方法
(4)使用shutdown() 方法结束线程池

注:(1)call() 中的返回值和Callable中的泛型是一致的
(2)submit() 方法相当于Thread中的start() 方法


线程池的优点:节约成本。很多子线程在调用完毕之后不会立即被回收掉,而是回到线程池中被多次利用








例1:submit(Callable<T> task)
// 自定义Callable类import java.util.concurrent.Callable;public class MyCallable implements Callable<Object> {@Overridepublic Object call() throws Exception {for (int i = 0; i < 10; i++) {System.out.println(Thread.currentThread().getName()+"---"+i);}return null;}}

// 测试类import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;public class CallableTest {public static void main(String[] args) {// 创建线程池对线,并指定2条线程 ExecutorService pool = Executors.newFixedThreadPool(2); // 提交Callable任务pool.submit(new MyCallable());pool.submit(new MyCallable());// 结束线程pool.shutdown();}}








例2:线程求和
// 自定义Callable类import java.util.concurrent.Callable;public class MyCallable implements Callable<Integer> {private int number;public MyCallable(int number) {this.number = number;}@Overridepublic Integer call() throws Exception { // 返回与Callable接口泛型一致// 定义最终结果变量int sum = 0;for (int x = 1; x <= number; x++) {sum += x;}return sum;}}

// 测试类import java.util.concurrent.ExecutorService;import java.util.concurrent.Executors;import java.util.concurrent.Future;import java.util.concurrent.ExecutionException;public class CallableTest {public static void main(String[] args) throws InterruptedException, ExecutionException {// 创建线程池对象,利用工厂类:ExecutorsExecutorService Pool = Executors.newFixedThreadPool(2);// 提交2个异步任务,分别计算1-100,1-200之间的和Future<Integer> future1 = Pool.submit(new MyCallable(100));Future<Integer> future2 = Pool.submit(new MyCallable(200));// 分别调用Future接口中 get()方法,返回具体的结果Integer v1 = future1.get();Integer v2 = future2.get();// 输出结果System.out.println("v1:" + v1);System.out.println("v2:" + v2);}}



阅读全文
0 0
原创粉丝点击