关闭

java Callable Future

81人阅读 评论(0) 收藏 举报
分类:
@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<Integer> 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();
	}

}




0
0

查看评论
* 以上用户言论只代表其个人观点,不代表CSDN网站的观点或立场
    个人资料
    • 访问:13221次
    • 积分:695
    • 等级:
    • 排名:千里之外
    • 原创:58篇
    • 转载:6篇
    • 译文:0篇
    • 评论:3条
    文章分类
    最新评论