Java thread中的callback和Future的簡單使用
阿新 • • 發佈:2019-02-13
package threadPa;
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;
/**
* @author ltz:
* @version 上午11:43:37
* 類說明
*/
public class ThreadCallTest {
public static void main(String[]args){
ExecutorService exe=Executors.newCachedThreadPool();
Task task=new Task();
Future<Integer> result=exe.submit(task);
exe.shutdown();
try {
System.out.println("call result"+result.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("over");
}
}
class Task implements Callable<Integer>{
@Override
public Integer call() throws Exception {
System.out.println("begin ....");
Thread.sleep(3000);
return 100;
}
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;
/**
* @author ltz:
* @version 上午11:43:37
* 類說明
*/
public class ThreadCallTest {
public static void main(String[]args){
ExecutorService exe=Executors.newCachedThreadPool();
Task task=new Task();
Future<Integer> result=exe.submit(task);
exe.shutdown();
try {
System.out.println("call result"+result.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
System.out.println("over");
}
}
class Task implements Callable<Integer>{
@Override
public Integer call() throws Exception {
System.out.println("begin ....");
Thread.sleep(3000);
return 100;
}
}
我們先來看一下FutureTask的實現:
1 |
public class FutureTask<V> implements RunnableFuture<V>
|
FutureTask類實現了RunnableFuture介面,我們看一下RunnableFuture介面的實現:
1 2 3 |
public interface RunnableFuture<V> extends Runnable,
Future<V> {
void run();
}
|
可以看出RunnableFuture繼承了Runnable介面和Future介面,而FutureTask實現了RunnableFuture介面。所以它既可以作為Runnable被執行緒執行,又可以作為Future得到Callable的返回值。
FutureTask提供了2個構造器:
1 2 3 4 |
public FutureTask(Callable<V>
callable) {
}
public FutureTask(Runnable
runnable, V result) {
}
|
事實上,FutureTask是Future介面的一個唯一實現類。