标签:ttl throw 服务 executor callable result 两种方法 href main
参考LittleCadet的博客多线程中Future与FutureTask的区别和联系
线程创建的两种方法,一种是实现Runnable接口,另一种是继承Thread。二者无法获取返回结果,于是有Callable接口,Future接口与FutureTask类的配和取得返回的结果。
FutureTask 实现了 Future接口。
相同的FutureTask对象,只会被执行一次,来保证任务的唯一性,且线程安全。
public class FutureTask<V> extends Object implements RunnableFuture<V>
1、使用线程池执行服务
使用Future接口
package com.thread.demo1;
import java.util.concurrent.*;
//使用线程池执行服务
public class FutureTest {
public static void main(String[] args) {
MyThread myThread = new MyThread();
//创建线程池
//ExecutorService ser = Executors.newFixedThreadPool(1);//参数为池大小
ExecutorService ser = Executors.newSingleThreadExecutor();//一个线程的线程池
//提交执行
Future<Integer> f1 = ser.submit(myThread);
//获取返回结果
int result = 0;
try {
result = f1.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
//关闭线程池
ser.shutdown();
System.out.println(result);
}
}
class MyThread implements Callable<Integer> {
@Override
public Integer call() throws Exception {
System.out.println("MyThread");
return 100;
}
}
使用FutureTask类
package com.thread.demo1;
import java.util.concurrent.*;
public class FutureTaskTest {
public static void main(String[] args) {
//使用线程池执行服务
MyThread2 myThread2 = new MyThread2();
//创建线程池
//ExecutorService ser = Executors.newFixedThreadPool(1);//参数为池大小
ExecutorService ser = Executors.newSingleThreadExecutor();//一个线程的线程池
//创建FutureTask对象
FutureTask<Integer> f2 = new FutureTask<Integer>(myThread2);
//提交执行
ser.submit(f2);
//获取返回结果
int result = 0;
try {
result = f2.get();
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
//关闭线程池
ser.shutdown();
System.out.println(result);
}
}
class MyThread2 implements Callable<Integer> {
@Override
public Integer call() throws Exception {
System.out.println("MyThread2");
return 100;
}
}
2、通过Future和Thread
package com.thread.demo1;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.FutureTask;
public class CallableTest {
public static void main(String[] args) {
MyThread3 myThread3 = new MyThread3();
FutureTask<Integer> f3 = new FutureTask<Integer>(myThread3);
new Thread(f3).start();
int result = 0;
try {
result = f3.get();
System.out.println(result);
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}
}
class MyThread3 implements Callable<Integer> {
@Override
public Integer call() throws Exception {
System.out.println("MyThread3");
return 100;
}
}
标签:ttl throw 服务 executor callable result 两种方法 href main
原文地址:https://www.cnblogs.com/sgKurisu/p/14417527.html