建立java线程,咱们常用两种方式:java
但这两种方式有一个缺陷:在执行完任务以后没法直接获取执行结果。ide
public interface Callable<V> { V call() throws Exception; }
public interface Runnable { public abstract void run(); }
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 class FutureTask<V> implements RunnableFuture<V>
public interface RunnableFuture<V> extends Runnable, Future<V> { void run(); }
Runnable runnable = new Runnable() { @Override public void run() { System.out.println("线程执行中..."); } }; Thread thread = new Thread(runnable); thread.start();
Callable < Integer > callable = new Callable < Integer > () { @Override public Integer call() throws Exception { System.out.println("线程执行中..."); return 100; } }; FutureTask < Integer > futureTask = new FutureTask < Integer > (callable); new Thread(futureTask).start(); // 等待1秒,让线程执行 TimeUnit.SECONDS.sleep(1); if(futureTask.isDone()) { System.out.println("获取执行结果:" + futureTask.get()); }
Callable < Integer > callable = new Callable < Integer > () { @Override public Integer call() throws Exception { System.out.println("线程执行中..."); return 100; } }; ExecutorService service = Executors.newCachedThreadPool(); Future < Integer > future = service.submit(callable); // 等待1秒,让线程执行 TimeUnit.SECONDS.sleep(1); if(futureTask.isDone()) { System.out.println("获取执行结果:" + future.get()); }