java使用Callable创建又返回值的线程

时间:2023-03-09 05:25:27
java使用Callable创建又返回值的线程
并发编程使我们可以将程序分为很多个分离的,相互之间独立的任务,通过使用多线程的机制,将每个任务都会有一个执行线程来单独的驱动,一个线程是 进程中一个单一顺序控制流,一个进程可以拥有多个线程,也就相当于有多个单独的顺序控制流,所以你的进程当中每个线程看起来都是有单独的cpu一样,底层实现就是切分cpu的时间片。
实现线程的方法
1 直接继承Thread类 然后重写run方法 局限性特别大 因为 任何一个类都只能继承一个父类 继承了线程 不可以继承其他类
2 继承Runnable 接口 重写run方法 r然后将 这个类的实例 当作参数传给Thread的构造器 创建线程这种方法 优于上面的方法 接口可以继承任意数量
但是上述两种方式 都有一个缺点那就是线程执行后是没有返回值的
为了实现在线程执行后 返回结果集 引进一种新的方式 实现Callable接口
实现Callable接口 实现了 会返回结果 可以在从线程执行的时候使用funture 来接收返回值!
下面是实现线程的代码
package test.link.thread;

import java.util.concurrent.Callable;

/**
* Callable<T> T的类型就是你要返回对象的类型!
* @author Administrator
*
*/
class TaskWithResult implements Callable<String> {
private static int num;
private int id;
public TaskWithResult() {
id = num++;
System.out.println("线程#"+id+"开始初始化");
}
@Override
public String call() throws Exception {
for(int i=0;i<3;i++){
System.out.println("call ing...");
}
System.out.println("线程#"+id+"即将结束");
return "Results of Task: "+id;
} }

下面是如何接收线程返回值的代码

package test.link.thread;

import java.util.ArrayList;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future; public class Demo {
public static void main(String[] args) {
ExecutorService exc = Executors.newCachedThreadPool();
ArrayList<Future<String>> res = new ArrayList<Future<String>>();
res.add(exc.submit(new TaskWithResult()));
for(Future<String > r: res){
try {
System.out.println(r.get());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (ExecutionException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}finally {
exc.shutdown();
}
} }
}