Java异步调用模式

在长期的Java客户端开发中,最常见的一个客户端调用模式就是Java的异步调用。所谓异步调用其实就是实现一个可无需等待被调用函数的返回值而让操作继续运行的方法。在Java语言中,简单的讲就是另启一个线程来完成调用中的部分计算,使调用继续运行或返回,而不需要等待计算结果。但调用者仍需要取线程的计算结果。虽然在1.5以前从异步线程中取得返回结果需要自己精心设计,但从JDK1.5开始引入了Future接口(FutureTask类)从异步执行的线程中取得返回值。 Future 表示异步计算的结果,它提供了检查计算是否完成的方法,以等待计算的完成,并获取计算的结果。FutureTask类是Future接口方法的一个基本实现,是一种可以取消的异步计算任务,计算是通过Callable接口来实现的。

FutureTask有下面几个重要的方法:

       1. get()   阻塞一直等待执行完成拿到结果

       2. get(int timeout, TimeUnit timeUnit)  阻塞一直等待执行完成拿到结果,如果在超时时间内,没有拿到抛出异常

       3. isCancelled()  是否被取消

       4. isDone()   是否已经完成

       5. cancel(boolean mayInterruptIfRunning)  试图取消正在执行的任务

Callable和Runnable有几点不同:

  • Callable规定的方法是call(),而Runnable规定的方法是run().
  • Callable的任务执行后可返回值,而Runnable的任务是不能返回值的。
  • call()方法可抛出异常,而run()方法是不能抛出异常的。

运行Callable任务可拿到一个Future对象,通过Future对象可了解任务执行情况,可取消任务的执行,还可获取任务执行的结果。 举一个例子说明如何使用Future对象,如下:

public class MyFutureTaskTest {
    public static void main(String[] args) {
        ExecutorService executor = Executors.newCachedThreadPool();
        FutureTask<String> future = new FutureTask<String>(new Callable<String>() {
            public String call() throws Exception{ //建议抛出异常
                try {
                    Thread.sleep(5* 1000);
                    return “Hello Welcome!”;
                }
                catch(Exception e) {
                    throw new Exception(“Callable terminated with Exception!”); // call方法可以抛出异常
                }
            }
        });
        executor.execute(future);
        long t = System.currentTimeMillis();
        try {

//            String result = future.get(3000, TimeUnit.MILLISECONDS); //取得结果,同时设置超时执行时间为5秒。
            String result = future.get(); //取得结果,同时设置超时执行时间为5秒。
            System.err.println(“result is ” + result + “, time is ” + (System.currentTimeMillis() – t));
        } catch (InterruptedException e) {
            future.cancel(true);
            System.err.println(“Interrupte time is ” + (System.currentTimeMillis() – t));
        } catch (ExecutionException e) {
            future.cancel(true);
            System.err.println(“Throw Exception time is ” + (System.currentTimeMillis() – t));
//        } catch (TimeoutException e) {
//            future.cancel(true);
//            System.err.println(“Timeout time is ” + (System.currentTimeMillis() – t));
        } finally {
            executor.shutdown();
        }

    }
}

运行结果如下:

 result is Hello Welcome!, time is 5000

如果设置了超时时间,则运行结果如下:

Timeout time is 3000

 可以看出设置超时时间的影响。

再如一个多个运行任务的例子:

public class MyAsyncExample implements Callable {
    private int num;

    public MyAsyncExample(int aInt) {
        this.num = aInt;
    }

    public String call() throws Exception {
        boolean resultOk = false;
        if (num == 0) {
            resultOk = true;
        } else if (num == 1) {
            while (true) { //infinite loop
                System.out.println(“looping….”);
                Thread.sleep(3000);
            }
        } else {
            throw new Exception(“Callable terminated with Exception!”); 
        }
        if (resultOk) {
            return “Task done.”;
        } else {
            return “Task failed”;
        }
    }

    public static void main(String[] args) {
        //定义几个任务
        MyAsyncExample call1 = new MyAsyncExample(0);
        MyAsyncExample call2 = new MyAsyncExample(1);
        MyAsyncExample call3 = new MyAsyncExample(2);
        //初始任务执行工具。
        ExecutorService es = Executors.newFixedThreadPool(3);
        //执行任务,任务启动时返回了一个Future对象,
        Future future1 = es.submit(call1);
        Future future2 = es.submit(call2);
        Future future3 = es.submit(call3);
        try {
            //任务1正常执行完毕,future1.get()会返回线程的值
            System.out.println(future1.get());
            //任务2进行一个死循环,调用future2.cancel(true)来中止此线程。
            Thread.sleep(3000);
            System.out.println(“Thread 2 terminated? :” + future2.cancel(true));
            //任务3抛出异常,调用future3.get()时会引起异常的抛出
            System.out.println(future3.get());
        } catch (ExecutionException ex) {
            ex.printStackTrace();
        } catch (InterruptedException ex) {
            ex.printStackTrace();
        }
    }
}

 运行结果如下:

looping….
Task done.
java.util.concurrent.ExecutionException: java.lang.Exception: Callable terminated with Exception!
 at java.util.concurrent.FutureTask$Sync.innerGet(FutureTask.java:222)
looping….
 at java.util.concurrent.FutureTask.get(FutureTask.java:83)
Thread 2 terminated? :true
 at org.jevo.future.sample.MyAsyncExample.main(MyAsyncExample.java:57)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
 at java.lang.reflect.Method.invoke(Method.java:597)
 at com.intellij.rt.execution.application.AppMain.main(AppMain.java:90)
Caused by: java.lang.Exception: Callable terminated with Exception!
 at org.jevo.future.sample.MyAsyncExample.call(MyAsyncExample.java:30)
 at org.jevo.future.sample.MyAsyncExample.call(MyAsyncExample.java:13)
 at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:303)
 at java.util.concurrent.FutureTask.run(FutureTask.java:138)
 at java.util.concurrent.ThreadPoolExecutor$Worker.runTask(ThreadPoolExecutor.java:886)
 at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:908)
 at java.lang.Thread.run(Thread.java:662)

以上是对Future模型的例子。异步调用在Swing中应该十分广泛,当客户端调用一个’重’的服务端操作时,我们常采用这种方式。Swing中存在一个Future的实现——SwingWorker,这使我们十分方便地在客户端开发中使用异步调用,详细使用参见API文档。下面附一个不使用Future来实现取得异步调用的代码,如下:

public abstract class AsyncWorker {
    private Object value;  //the running result
    private boolean finished = false;

    private static class ThreadVar {
        private Thread thread;

        ThreadVar(Thread t) {
            thread = t;
        }

        synchronized Thread get() {
            return thread;
        }

        synchronized void clear() {
            thread = null;
        }
    }

    private ThreadVar threadVar;

    /**
     * 返回当前线程运行结果。
     */
    protected synchronized Object getValue() {
        return value;
    }

    /**
     * 设置当前线程运行结果
     */
    private synchronized void setValue(Object x) {
        value = x;
    }

    /**
     * 调用都创建计算逻辑,将运算结果返回
     */
    public abstract Object construct();

    public void finished() {
        finished = true;
    }

    public boolean isFinished() {
        return finished;
    }

    public void interrupt() {
        Thread t = threadVar.get();
        if (t != null) {
            t.interrupt();
        }
        threadVar.clear();
    }

    public void stop() {
        Thread t = threadVar.get();
        if(t!=null) {
            t.stop();
        }
        threadVar.clear();
    }

    /**
     * 返回 construct方法运行结果。
     */
    public Object get() {
        while (true) {
            Thread t = threadVar.get();
            if (t == null) {
                return getValue();
            }
            try {
                t.join();
            }
            catch (InterruptedException e) {
                Thread.currentThread().interrupt();
                return null;
            }
        }
    }

    public AsyncWorker() {
        final Runnable doFinished = new Runnable() {
            public void run() {
                finished();
            }
        };

        Runnable doConstruct = new Runnable() {
            public void run() {
                try {
                    setValue(construct());
                }
                finally {
                    threadVar.clear();
                }

                SwingUtilities.invokeLater(doFinished);
            }
        };

        Thread t = new Thread(doConstruct);
        threadVar = new ThreadVar(t);
    }

    /**
     * Start the worker thread.
     */
    public void start() {
        finished = false;
        Thread t = threadVar.get();
        if (t != null) {
            t.start();
        }
    }

    public static void main(String[] args) {
        AsyncWorker worker = new AsyncWorker() {
            public Object construct() {
                try {
                    Thread.sleep(3*1000);
                }
                catch(Exception e){}
                return “hello world”;

            }

            public void finished() {
                super.finished();
                //取线程运行返回的结果
//                Object obj = this.get();
//                System.err.println(“return is ” + obj);
            }
        };

        long t = System.currentTimeMillis();
        worker.start();
        Object obj = worker.get(); //取得运行结果
        System.err.println(“return is ” + obj + “, time = ” + (System.currentTimeMillis() – t));

    }
}

在上述代码中,调用者只需要扩展AsyncWorker类定义可计算的逻辑,并将逻辑结果返回。返回结果会保存在一变量中。当调用者调用返回结果时,如果计算还未完成,将调用Thread.join()阻塞线程,直到计算结果返回。用法上是不是与FutureTask相似?在Swing异步调用中,还需要结合等待对话框来表示计算运行进程,从而使运行界面显示更加友好。 

再看一下线程的join方法,我们知道线程可被Object.wait、Thread.join和Thread.sleep三种方法之一阻塞,当接收到一个中断异常(InterruptedException)时,可提早地终结被阻塞状态。Thread.join的使用情况却有所不同:我们对一些耗时运算,常启用一个主线程来生成并启动一些子线程,在子线程中进行耗时的运算,当主线程继续处理完其他的事务后,需要调用子线程的处理结果,这个时候就要使用join();。Joint方法将使主线程等待子线程运行结束,即join()方法后的代码,只有等到子线程运行结束后才能被执行。参考下例:

public class ChildThread extends Thread {
    public ChildThread() {
        super(“ChildThread”);
    }

    public void run() {
        String threadName = Thread.currentThread().getName();
        System.out.println(threadName + ” start.”);
        try {
            for (int i = 0; i < 5; i++) {
                System.out.println(threadName + ” loop at ” + i);
                Thread.sleep(1000);
            }
            System.out.println(threadName + ” end.”);
        } catch (Exception e) {
            System.out.println(“Exception from ” + threadName + “.run”);
        }
    }
}

 

public class ParentThread extends Thread {
    ChildThread t1;

    public ParentThread(ChildThread t1) {
        super(“ParentThread”);
        this.t1 = t1;
    }

    public void run() {
        String threadName = Thread.currentThread().getName();
        System.out.println(threadName + ” start.”);
        try {
            t1.join();   //ChildThread 线程t1结束后,才能运行此行代码后的代码。
            System.out.println(threadName + ” end.”);
        } catch (Exception e) {
            System.out.println(“Exception from ” + threadName + “.run”);
        }
    }

    public static void main(String[] args) {
        String threadName = Thread.currentThread().getName();
        System.out.println(threadName + ” start.”);
        ChildThread t1 = new ChildThread();
        ParentThread t = new ParentThread(t1);
        try {
            t1.start();
            Thread.sleep(2000);
            t.start();
            t.join();//此处注释后,将直接运行到结束代码. 注释此处代码,比较运行结果
        } catch (Exception e) {
            System.out.println(“Exception from main”);
        }
        System.out.println(threadName + ” end!”);
    }

}

在t.join()被注释前运行结果如下:

main start.
ChildThread start.
ChildThread loop at 0
ChildThread loop at 1
ParentThread start.
ChildThread loop at 2
ChildThread loop at 3
ChildThread loop at 4
ChildThread end.
ParentThread end.
main end!

当t.join()被注释后运行结果如下: 

main start.
ChildThread start.
ChildThread loop at 0
ChildThread loop at 1
main end!
ParentThread start.
ChildThread loop at 2
ChildThread loop at 3
ChildThread loop at 4
ChildThread end.
ParentThread end.

可见ParentThread线程仍等待ChildThread线程运行结束后才运行完毕,而Main线程与ParentThread线程的运行并没有保持等待。

 

    原文作者:Jevo
    原文地址: http://www.cnblogs.com/jevo/archive/2013/04/11/3015023.html
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞