java 线程 call 查询,java线程中Callble和Future的使用 | 学步园

Callable是java.util.concurrent包中一个接口,Callable 接口类似于Runnable,两者都是为那些其实例可能被另一个线程执行的类设计的。但是Runnable

不会返回结果,并且无法抛出经过检查的异常。此接口中就声明了一个方法call(),这个方法计算结果,如果无法计算结果,则抛出一个异常。Executors类包含一些从其他普通形式转换成Callable类的实用方法。我们来看看此接口和它方法声明的源码(JDK1.6):

public interface Callable {

/**

* Computes a result, or throws an exception if unable to do so.

*

* @return computed result

* @throws Exception if unable to compute a result

*/

V call() throws Exception;

}

Future也是java.util.concurrent包中一个接口,Future接口 表示异步计算的结果。它提供了检查计算是否完成的方法,以等待计算的完成,并获取计算的结果。计算完成后只能使用get()或者get(long timeout,TimeUnit unit) 方法来获取结果,如有必要,计算完成前可以阻塞此方法。取消则由cancel(boolean mayInterruptIfRunning)

方法来执行。还提供了其他方法,以确定任务是正常完成还是被取消了。一旦计算完成,就不能再取消计算。如果为了可取消性而使用Future 但又不提供可用的结果,则可以声明Future> 形式类型、并返回null作为底层任务的结果, FutureTask

类是Future 的一个实现。我们来看看源码(JDK1.6):

public interface Future {

/**

* Attempts to cancel execution of this task. This attempt will

* fail if the task has already completed, already been cancelled,

* or could not be cancelled for some other reason. If successful,

* and this task has not started when cancel is called,

* this task should never run. If the task has already started,

* then the mayInterruptIfRunning parameter determines

* whether the thread executing this task should be interrupted in

* an attempt to stop the task.

*

*

After this method returns, subsequent calls to {@link #isDone} will

* always return true. Subsequent calls to {@link #isCancelled}

* will always return true if this method returned true.

*

* @param mayInterruptIfRunning true if the thread executing this

* task should be interrupted; otherwise, in-progress tasks are allowed

* to complete

* @return false if the task could not be cancelled,

* typically because it has already completed normally;

* true otherwise

*/

boolean cancel(boolean mayInterruptIfRunning);

/**

* Returns true if this task was cancelled before it completed

* normally.

*

* @return true if this task was cancelled before it completed

*/

boolean isCancelled();

/**

* Returns true if this task completed.

*

* Completion may be due to normal termination, an exception, or

* cancellation -- in all of these cases, this method will return

* true.

*

* @return true if this task completed

*/

boolean isDone();

/**

* Waits if necessary for the computation to complete, and then

* retrieves its result.

*

* @return the computed result

* @throws CancellationException if the computation was cancelled

* @throws ExecutionException if the computation threw an

* exception

* @throws InterruptedException if the current thread was interrupted

* while waiting

*/

V get() throws InterruptedException, ExecutionException;

/**

* Waits if necessary for at most the given time for the computation

* to complete, and then retrieves its result, if available.

*

* @param timeout the maximum time to wait

* @param unit the time unit of the timeout argument

* @return the computed result

* @throws CancellationException if the computation was cancelled

* @throws ExecutionException if the computation threw an

* exception

* @throws InterruptedException if the current thread was interrupted

* while waiting

* @throws TimeoutException if the wait timed out

*/

V get(long timeout, TimeUnit unit)

throws InterruptedException, ExecutionException, TimeoutException;

}

下边我们就通过一个例子来简单了解它们是如何使用的。

package CallableFuture;

import java.util.concurrent.Callable;

import java.util.concurrent.ExecutorService;

import java.util.concurrent.Executors;

import java.util.concurrent.Future;

import java.util.concurrent.TimeUnit;

import java.util.concurrent.TimeoutException;

public class CallableFutureTest {

public static void main(String[] args) {

// 定义3个Callable类型的任务

Callable task0 = new CallableTest(0);

Callable task1 = new CallableTest(1);

Callable task2 = new CallableTest(2);

ExecutorService es = Executors.newFixedThreadPool(3);// 创建一个执行任务的线程池

try {

Future future0 = es.submit(task0);// 提交并执行任务1,任务启动时返回了一个Future对象

System.out.println("task0执行结果 :" + future0.get());// 获得第一个任务的结果,如果调用get方法直到当前线程会等待任务执行完毕后才往下执行

Future future1 = es.submit(task1);// 提交并执行任务2,任务启动时返回了一个Future对象

String result1=null;

try{

result1=(String) future1.get(6,TimeUnit.SECONDS);// 如有必要,最多等待6秒之后,获取其结果(如果结果可用),因为此时任务在无限循环肯定超时

}catch(TimeoutException e){

System.out.println("future1用get获取超时了!此时任务1的执行结果:"+result1);

}

Future future2 = es.submit(task2);// 提交并执行任务2,任务启动时返回了一个Future对象

System.out.println("任务2开始执行了.....");

Thread.sleep(2000);//主线程即当前线程停止2秒往下执行

System.out.println("task1被cancel()取消任务,结果: " + future1.cancel(true));//中断任务1的循环

System.out.println("task2执行结果:" + future2.get());

} catch (Exception e){

System.out.println(e.toString());

}

// 停止任务执行服务

es.shutdownNow();

System.out.println("所有任务全部结束了!");

}

}

class CallableTest implements Callable{

public int testData = 0;

public CallableTest(int testData){

this.testData = testData;

}

@Override

public String call() throws Exception{

if (this.testData == 0){

return "testData = 0";

}

if (this.testData == 1){

try {

while (true) {

System.out.println("任务1执行中.....");

Thread.sleep(1000);

}

} catch (InterruptedException e) {

System.out.println("任务1中断了.....");

}

return "如果被cancle,则不会接受返回值!";

} else {

Thread.sleep(10000);

return "任务2睡了10秒!";

}

}

}

执行结果如下:

task0执行结果 :testData = 0

任务1执行中.....

任务1执行中.....

任务1执行中.....

任务1执行中.....

任务1执行中.....

任务1执行中.....

future1用get获取超时了!此时任务1的执行结果:null

任务2开始执行了.....

任务1执行中.....

任务1执行中.....

task1被cancel()取消任务,结果: true

任务1中断了.....

task2执行结果:任务2睡了10秒!

所有任务全部结束了!

最后,认真看过的网友们,大神们,如有感觉我这个程序猿有哪个地方说的不对或者不妥或者你有很好的

提议或者建议或点子方法,还望您大恩大德施舍n秒的时间留下你的宝贵文字(留言),以便你,我,还有广大的程序猿们更快地成长与进步.......

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值