Java中的Future

1.Future解决了什么问题

Future是java中的一个接口,主要用于java多线程计算过程的异步结果获取,能够感知计算的进度,与传统的多线程实现方式,比如继承Thread类,实现runnable接口,它们主要的局限在于对多线程运行的本身缺少监督。

2.Callable接口和Runnable接口区别

下面是它们之间的主要区别:

  1. runable接口是用run方法作为线程运行任务的入口,callable接口使用call方法
  2. call方法抛出异常,run方法不抛出异常,也就是说实现callable接口,可以对线程运行任务时的出错抛出的异常进行捕获,从而得知任务异常的原因
  3. 运行Callable任务可拿到一个Future对象, Future表示异步计算的结果
  4. callable的实现类FutureTask提供了检查计算是否完成的方法,以等待计算的完成,并检索计算的结果。

3.java实现线程的三种方式:

继承Thread类

class MyThread extends Thread{

private String str;

public MyThread(String str){

this.str = str;

}

public void run() {

for (int i = 0; i < 10; i++) {

System.out.println(this.str+"="+i);

}

}

}

public class Test {

public static void main(String[] args) {

new MyThread("线程一").start();

new MyThread("线程二").start();

new MyThread("线程三").start();

}

}

实现Runnable接口

public MyRunnable implements Runnable{ 
public void run(){ 
for(int i = 0;i<100;i++){ 
System.out.println(i); 
} 
} 
}

public class MyRunnableDemo{ 
public static void main(String[] args){ 
MyRunnable my = new MyRunnable(); 
Thread t1 = new Thread(my,”线程1”); 
Thread t2 = new Thread(my,”线程2”); 
t1.start(); 
t2.start(); 
} 
}

实现Callable接口

import java.util.concurrent.Callable;

import java.util.concurrent.ExecutionException;

import java.util.concurrent.FutureTask;

 

class MyThread implements Callable<String>{

private String title;

public MyThread(String title){

this.title = title;

}

public String call()throws Exception{

for (int i = 0; i < 10; i++) {

System.out.println(title+"i="+i);

}

return "线程执行完毕";

}

}

public class Test {

public static void main(String[] args) throws InterruptedException, ExecutionException {

FutureTask<String> task1 = new FutureTask<>(new MyThread("线程一"));

FutureTask<String> task2 = new FutureTask<>(new MyThread("线程二"));

new Thread(task1).start();

new Thread(task2).start();

System.out.println("线程返回数据一"+ task1.get());

System.out.println("线程返回数据二"+ task2.get());

}

}

三种实现方式都能够达到多线程运算的目的,但是适用场景却不同。
继承Thread类实现多线程是最为简洁的方式,但是由于Java是单继承,继承了Thread类就不能继承其他的类,影响了类的扩展性。

实现Runnable接口是为了规避ava单继承的问题,

实现Callable接口则是为了满足获取异步计算结果,对线程计算更为可控设计的。

4.实现callable接口如何使异步计算更为可控?

通常为了达到多线程并发运行任务,需要利用Java的Thread类,要么继承它,要么传递一个Runnable对象给Thread类,然后通过调用它的start方法,运行异步计算任务。那么实现callable的接口如何利用Thread类来达到多线程并发运行的目的呢?

答案是FutureTask,FutureTask类:包装callable接口,并同时实现了Runable接口和Future接口,实现Runnable接口是为了满足多线程并发执行的目的,实现Future接口则是为了满足多线程并发过程中新线程不可控问题。

FutureTask的构造方法:

    public FutureTask(Callable<V> callable) {
        if (callable == null)
            throw new NullPointerException();
        this.callable = callable;
        this.state = NEW;       // ensure visibility of callable
    }

从上面可以看出FutureTask类将Callable接口作为自己的私有成员变量,作为操作的起点。
而state则是FutureTask封装的callable实现类的call方法的状态变量,主要是了解异步任务的状态

它主要定义了6种状态,

     * Possible state transitions:
     * NEW -> COMPLETING -> NORMAL
     * NEW -> COMPLETING -> EXCEPTIONAL
     * NEW -> CANCELLED
     * NEW -> INTERRUPTING -> INTERRUPTED
     */
    private volatile int state;
    private static final int NEW          = 0;
    private static final int COMPLETING   = 1;
    private static final int NORMAL       = 2;
    private static final int EXCEPTIONAL  = 3;
    private static final int CANCELLED    = 4;
    private static final int INTERRUPTING = 5;
    private static final int INTERRUPTED  = 6;

根据它的命名可以很清楚的明白,各个常量所代表的含义。
NEW代表异步计算还没开始,
COMPLETING 代表计算正在进行中
NORMAL 代表计算正常结束
EXCEPTIONAL 代表计算过程中出现了异常
CANCELLED 代表计算任务被取消
INTERRUPTING 代表计算任务正在被中断执行
INTERRUPTED 代表计算任务已经被中断执行

接着来看,FutureTask的run方法实现:

  public void run() {
  		1。判断计算状态,如果不为NEW,结束
        if (state != NEW ||                            
            !UNSAFE.compareAndSwapObject(this, runnerOffset,
                                         null, Thread.currentThread()))
            return;
        try {
            Callable<V> c = callable;
            if (c != null && state == NEW) {
                V result;
                boolean ran;
                try {
                 //2 .执行实现Callable类的call方法
                    result = c.call();
                    ran = true;
                } catch (Throwable ex) {
                    result = null;
                    ran = false;
                    //3. 异常捕捉
                    setException(ex);
                }
                if (ran)
                	//4. 结果回显
                    set(result);
            }
        } finally {
            // runner must be non-null until state is settled to
            // prevent concurrent calls to run()
            runner = null;
            // state must be re-read after nulling runner to prevent
            // leaked interrupts
            int s = state;
            //5. 解决中断
            if (s >= INTERRUPTING)
                handlePossibleCancellationInterrupt(s);
        }
    }

从FutureTask的run方法,可以看出,它是在以自己作为新线程的入口,执行传递给自己的callable实现类的call方法,并将call方法的返回值保存在自己的私有成员变量中。

在上面代码3处,主要是做了异常封装的工作。

    protected void setException(Throwable t) {
        if (UNSAFE.compareAndSwapInt(this, stateOffset, NEW, COMPLETING)) {
            outcome = t;
            UNSAFE.putOrderedInt(this, stateOffset, EXCEPTIONAL); // final state
            finishCompletion();
        }
    }

outcome被设计为Object类型,这样它既可以接受异步计算的结果,又可以接受一个Exception异常,
finishCompletion();方法,主要是为了唤醒因调用get方法阻塞的线程。

 private void finishCompletion() {
        // assert state > COMPLETING;
        for (WaitNode q; (q = waiters) != null;) {
            if (UNSAFE.compareAndSwapObject(this, waitersOffset, q, null)) {
                for (;;) {
                    Thread t = q.thread;
                    if (t != null) {
                        q.thread = null;
                        LockSupport.unpark(t);
                    }
                    WaitNode next = q.next;
                    if (next == null)
                        break;
                    q.next = null; // unlink to help gc
                    q = next;
                }
                break;
            }
        }

        done();

        callable = null;        // to reduce footprint
    }

最后来看最为重要的get方法实现:

public V get() throws InterruptedException, ExecutionException {
        int s = state;
        if (s <= COMPLETING)
            s = awaitDone(false, 0L);
        return report(s);
    }

FutureTask主要用state变量来了解实现callable类的call方法计算的状态,当计算状态为开始NEW或者正在计算COMPLETING,那么需要考虑阻塞当前线程。阻塞是用awaitDown方法实现的。

 private int awaitDone(boolean timed, long nanos)
        throws InterruptedException {
        final long deadline = timed ? System.nanoTime() + nanos : 0L;
        WaitNode q = null;
        boolean queued = false;
        for (;;) {
            1. 在get阻塞中设置线程的interrupt标志位,可以使其跳出等待
            if (Thread.interrupted()) {
              2.将线程的waitor从等待链表中移除
                removeWaiter(q);
                throw new InterruptedException();
            }
			3.如果进入方法后查看state,发现state已经大于计算中,则可以退出等待返回结果
            int s = state;
            if (s > COMPLETING) {
                if (q != null)
                    q.thread = null;
                return s;
            }
            4. 如果快计算完,降低线程优先级,降低获取CPU可能性
            else if (s == COMPLETING) // cannot time out yet
                Thread.yield();
            else if (q == null)
                q = new WaitNode();
            else if (!queued)
                queued = UNSAFE.compareAndSwapObject(this, waitersOffset,
                                                     q.next = waiters, q);
            else if (timed) {
                nanos = deadline - System.nanoTime();
                if (nanos <= 0L) {
                    removeWaiter(q);
                    return state;
                }
                LockSupport.parkNanos(this, nanos);
            }
            else   阻塞线程
                LockSupport.park(this);
        }
    }
  • 6
    点赞
  • 22
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
JavaFuture是用于异步计算的接口。它代表了一个可获取结果的异步操作,并提供了方法来检查操作是否完成、等待操作完成并获取结果。使用Future,我们可以在一个线程启动一个耗时的任务,在另一个线程继续执行其他操作,待任务完成后再获取其结果。 Future接口定义了以下主要方法: - `boolean isDone()`: 判断任务是否已完成。 - `boolean cancel(boolean mayInterruptIfRunning)`: 尝试取消任务的执行。 - `boolean isCancelled()`: 判断任务是否已被取消。 - `V get() throws InterruptedException, ExecutionException`: 等待任务完成并获取结果。 - `V get(long timeout, TimeUnit unit) throws InterruptedException, ExecutionException, TimeoutException`: 在指定时间内等待任务完成并获取结果。 Future接口的实现类是FutureTask,它可以通过Callable或Runnable任务来创建。我们可以使用ExecutorService.submit()方法提交任务并返回一个Future对象,通过该对象可以获取任务的执行结果。 以下是一个使用Future的简单示例: ```java import java.util.concurrent.*; public class FutureExample { public static void main(String[] args) { ExecutorService executor = Executors.newFixedThreadPool(1); Future<Integer> future = executor.submit(() -> { Thread.sleep(2000); return 42; }); // 执行其他操作 try { Integer result = future.get(); // 阻塞等待任务执行完成,并获取结果 System.out.println("任务结果:" + result); } catch (InterruptedException | ExecutionException e) { e.printStackTrace(); } executor.shutdown(); } } ``` 在上面的例子,我们使用ExecutorService提交一个任务,该任务会在2秒后返回结果42。在主线程执行其他操作后,通过future.get()方法阻塞等待任务的完成,并获取其结果。 需要注意的是,如果任务已经完成,调用get()方法会立即返回结果,否则会阻塞等待任务完成。如果我们希望在指定时间内获取结果,可以使用带有超时参数的get()方法。 这就是关于JavaFuture的简单介绍。希望能对你有所帮助!如果你还有其他问题,请继续提问。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值