from:http://www.blogjava.net/sitinspring/archive/2007/06/28/126809.html
现在程序中有许多涉及长耗时响应过程的处理,比如访问WebService,远程调用,复杂处理等,如果我们使用直接顺序执行的方式进行处理有可能导致界面停顿,响应停止,无谓等待等缺陷,这是不应该的。
一个耗时响应过程应该采用回调和线程来处理,具体就是把原来的顺序执行修改为异步方式,并让被调用者调用调用者以获得执行结果。在附件的例子中,Viewer就是调用者,它代表界面,而LongTimeResponse是被调用者,它内部用线程启动一个耗时过程,执行完毕再通知调用者。
Viewer类代码如下:


public
?
class
?Viewer

{

????private?int?count;

????


????public?Viewer(int?count)
{

????????this.count=count;

????}

????


????public?void?printNewCount(int?newCount)
{

????????System.out.println("New?Count="+newCount);

????}



????public?int?getCount()?
{

????????return?count;

????}



????public?void?setCount(int?count)?
{

????????this.count?=?count;

????}

}
LongTimeResponse类代码如下,可以看出,它之所以能回调调用者,是因为其内部有调用者的引用viewer,在其构造函数中viewer被赋上了值:

package
?com.sitinspring;



public
?
class
?LongTimeResponse?
implements
?Runnable

{

????private?Viewer?viewer;

????private?int?count;

????


????public?LongTimeResponse(Viewer?viewer)
{

????????this.viewer=viewer;

????????this.count=viewer.getCount();

????????

????????caculateNewCount();

????}

????


????private?void?caculateNewCount()
{

????????Thread?thread=new?Thread(this);

????????thread.start();

????}

????


????public?void?run()
{


????????try
{

????????????Thread.sleep(10000);????

????????}


????????catch(Exception?ex)
{

????????????ex.printStackTrace();

????????}

????????

????????viewer.printNewCount(count*count*count);

????}

}
?
调用过程如下:

????????Viewer?viewer
=
new
?Viewer(
10
);

????????LongTimeResponse?longTimeResponse
=
new
?LongTimeResponse(viewer);????????

????????viewer.printNewCount(
123
);
执行起来可以看出,程序先输出了
New Count=123
过了十秒,才输出:
New Count=1000
这说明,程序是异步执行的,耗时过程没有影响到主干程序的运行,而耗时过程完成后,才把返回结果通知了调用者,主干程序没有受到耗时过程的影响,因此也就不会导致界面停顿,响应停止,无谓等待等缺陷。
以上就是使用回调和线程处理一个耗时响应的整个过程。
这里可下载整个程序:
http://www.blogjava.net/Files/sitinspring/Callback20070628133516.zip
?