天天看点

java每日总结

Java中的Runable,Callable,Future,FutureTask,ExecutorService,Excetor,Excutors,ThreadPoolExcetor在这里对这些关键词,以及它们的用法做一个总结。

首先将它们分个类:

Runable,Callable

Future,FutureTask

ExecutorService,Executor,Excutors,ThreadPoolExcetor

关于Ranable和Callable

首先Java中创建线程的方法有三种:

继承Thread类,覆盖run方法

实现Runable接口,实现run方法

实现Callable接口,实现run方法

三种实现的优缺点:

继承Thread,单继承的缘故,不能再继承其他类,获取当前线程this

实现Runable接口,没有返回值,获取当前线程Thread.currentThread()

实现Callable接口,可通过Future.get()获取返回值,获取当前线程 Thread.currentThread()

继承Thread,两个步骤:

class DemoThread extends Thread {    

@Override    

public void run() {        

super.run();        

// Perform time-consuming operation...   

 } }//加入Java开发交流君样:756584822一起吹水聊天

DemoThread t = new DemoThread(); t.start();

继承Thread类,覆盖run()方法。

创建线程对象并用start()方法启动线程。

实现Runable,一般使用如下:

new Thread(new Runnable() {    

// do something    

} }).start();

为了简单。

以上两种方式获取线程执行的结果相当麻烦,不能直接获取。JDK1.5增加了 Callable, Callable 的 call() 方法可以返回值和抛出异常。Callable 可以返回装载有计算结果的 Future 对象。

Callable的源码:

public interface Callable<V> {    

V call() throws Exception;

 }

Callable的基本使用方法:

FutureTask<Integer> futureTask = new FutureTask<Integer>(new Callable<Integer>() {    @Override    

public Integer call() throws Exception {        

// do something        

return null;    

} }); Thread thread = new Thread(futureTask); thread.start();

Integer result = futureTask.get();

运行 Callable 任务可以拿到一个 Future 对象,通过Future的get()方法拿到线程执行的返回值。那么...Future,FutureTask区别是什么,怎么使用?

->next()

关于Future和FutureTask

为了获取线程的执行结果,引入了Future的FutureTask,那么他们是什么关系,如何使用?

Future类位于java.util.concurrent包下,它是一个接口:

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;

 }//加入Java开发交流君样:756584822一起吹水聊天

Future 定义了5个方法:

boolean cancel(boolean

mayInterruptIfRunning):试图取消对此任务的执行。如果任务已完成、或已取消,或者由于某些其他原因而无法取消,则此尝试将失败。当调用

cancel() 时,如果调用成功,而此任务尚未启动,则此任务将永不运行。如果任务已经启动,则

mayInterruptIfRunning 参数确定是否应该以试图停止任务的方式来中断执行此任务的线程。此方法返回后,对

isDone() 的后续调用将始终返回 true。如果此方法返回 true,则对 isCancelled() 的后续调用将始终返回

true。

boolean isCancelled():如果在任务正常完成前将其取消,则返回 true。