在JAVA中如何实现长时间任务(二)

2014-11-23 23:22:34 · 作者: · 浏览: 2
处理这些异常。

The run() method has two levels of try-catch clause: outside and inside the
while-loop. The first try-catch clause is meant to catch all nonprogrammed
exceptions and guarantee that the run() method never exits. The second clause
will catch any kind of exceptions belonging to business logic and behave
accordingly. If some waiting operation takes place in the work() method (e.g.,
waiting on an InputStream or a Socket), it is advisable to propagate an
InterruptedException. The thing to keep in mind is that the work() method does
not need to have any while-loop to keep it going as long as an application
runs. The Worker does this for you.

run()方法有内外两层try-catch语句:一层处于while-loop循环外,一层在while-loop循
环内。前一个try-catch用于捕获非编程异常以确保run()方法不退出。后一个try-catch语
句捕获关于业务逻辑和相应行为的各种异常。如果在work()方法中发生了一些等待操作
(例如等待一个输入流或一个Socket),抛出一个InterruptedException的方法是可取
的。要记住的是只要应用程序在运行,work()方法不需要任何while-loop循环去维持它运
行,这一切由Worker代办了。

When the run() method starts, it calls the prepareWorker() which is designed
to prepare all resources needed for a long-running task (Listing A). In this
method call, you can, for example, establish a database connection or open a
file that will be used further. It is especially good to place here some
blocking operations like opening a socket, because they will be done