java Callable Future

@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();
	}

}




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值