使用回调和线程处理一个耗时响应过程
from:http://www.blogjava.net/sitinspring/archive/2007/06/28/126809.html 现在程序中有许多涉及长耗时响应过程的处理,比如访问WebService,远程调用,复杂处理等,如果我们使用直接顺序执行的方式进行处理有可能导致界面停顿,响应停止,无谓等待等缺陷,这是不应该的。
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; ????} }
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 );
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |