您的位置:首页 > 编程语言 > Java开发

java Callable Future

2016-06-01 16:36 363 查看
@FunctionalInterface
public interface Runnable {
public abstract void run();
}

@FunctionalInterface
public interface Callable<V> {
V call() throws Exception;
}

<pre name="code" class="java">public interface Future<V> {
boolean cancel(boolean mayInterruptIfRunning);

boolean isCancelled();

 boolean isDone();

 V get() throws InterruptedException, ExecutionException;

 V get(long timeout, TimeUnit unit)

        throws InterruptedException, ExecutionException, TimeoutException;

}

public interface RunnableFuture<V> extends Runnable, Future<V> {

    /**

     * Sets this Future to the result of its computation

     * unless it has been cancelled.

     */

    void run();

}



package com.provider.future;

import java.util.Random;
import java.util.concurrent.Callable;

public class Task implements Callable<Integer>{

public Integer call() throws Exception {
Thread.sleep(10000);
Random r = new Random();
return r.nextInt(1000);
}

}

package com.provider.future;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;
import java.util.concurrent.FutureTask;

public class TestFu {

public void fun1(){
ExecutorService executorService = Executors.newFixedThreadPool(2);
Future<Integ
b7c9
er> submit = executorService.submit(new Task());
executorService.shutdown();

System.out.println(submit.isDone());
try {
Thread.sleep(1500);
System.out.println(submit.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}

public void fun2(){
ExecutorService executorService = Executors.newFixedThreadPool(2);
FutureTask<Integer> ft = new FutureTask<Integer>(new Task());
executorService.submit(ft);
executorService.shutdown();
System.out.println(ft.isDone());
try {
Thread.sleep(1500);
System.out.println(ft.get());
} catch (InterruptedException e) {
e.printStackTrace();
} catch (ExecutionException e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
TestFu testFu =new TestFu();
testFu.fun1();
testFu.fun2();
}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: