Java并发-执行器Callable,Future
2016-05-15 22:20
302 查看
执行器:用于启动并控制线程的执行!核心接口为Executor,ExecutorService
一、Callable 与 Future执行器
Callable<V>:表示具有返回值的线程
V:表示返回值类型
call() : 执行任务
Future<V>: 表示Callable 的返回值
V:表示返回值类型
get() : 获取返回值
以下代码演示该执行器:
package com.executor.src;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Edemo {
public static void main(String[] args) throws InterruptedException, ExecutionException {
// 创建一个有两个线程的线程池
ExecutorService es = Executors.newFixedThreadPool(2);
// 创建两个任务提交给callable
Future<Integer> r1 = es.submit(new EX(1, 100));
Future<Integer> r2 = es.submit(new EX(100, 10000));
System.out.println(r1.get() + " : " + r2.get());
// 关闭执行器
es.shutdown();
}
}
class EX implements Callable<Integer>{
private int begin,end;
public EX(int begin,int end) {
this.begin = begin;
this.end = end;
}
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = begin; i < end; i++) {
sum += i;
}
return sum;
}
}
执行结果:
4950 : 49990050
一、Callable 与 Future执行器
Callable<V>:表示具有返回值的线程
V:表示返回值类型
call() : 执行任务
Future<V>: 表示Callable 的返回值
V:表示返回值类型
get() : 获取返回值
以下代码演示该执行器:
package com.executor.src;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
public class Edemo {
public static void main(String[] args) throws InterruptedException, ExecutionException {
// 创建一个有两个线程的线程池
ExecutorService es = Executors.newFixedThreadPool(2);
// 创建两个任务提交给callable
Future<Integer> r1 = es.submit(new EX(1, 100));
Future<Integer> r2 = es.submit(new EX(100, 10000));
System.out.println(r1.get() + " : " + r2.get());
// 关闭执行器
es.shutdown();
}
}
class EX implements Callable<Integer>{
private int begin,end;
public EX(int begin,int end) {
this.begin = begin;
this.end = end;
}
@Override
public Integer call() throws Exception {
int sum = 0;
for (int i = begin; i < end; i++) {
sum += i;
}
return sum;
}
}
执行结果:
4950 : 49990050
相关文章推荐
- C#线程间不能调用剪切板的解决方法
- C#线程同步的三类情景分析
- C#获取进程或线程相关信息的方法
- 简单对比C#程序中的单线程与多线程设计
- C#停止线程的方法
- C#子线程更新UI控件的方法实例总结
- C#线程队列用法实例分析
- C++使用CriticalSection实现线程同步实例
- 基于C++实现的线程休眠代码
- VB读取线程、句柄及写入内存的API代码实例
- C#网络编程基础之进程和线程详解
- C#通过Semaphore类控制线程队列的方法
- C#多线程处理多个队列数据的方法
- C#实现线程安全的简易日志记录方法
- C#中线程同步对象的方法分析
- ASP.NET线程相关配置
- 浅析linux环境下一个进程最多能有多少个线程
- 再谈JavaScript线程
- C#实现终止正在执行的线程
- Java线程编程中的主线程讲解