許多Web應用
當JSP調用一個必須長時間運行的操作
本文介紹的技術是把繁重的計算任務分離開來
一
首先我們設計一個TaskBean類
packagetest
importjava
publicclassTaskBeanimplementsRunnable
privateintcounter;
privateintsum;
privatebooleanstarted;
privatebooleanrunning;
privateintsleep;
publicTaskBean(){
counter=
sum=
started=false;
running=false;
sleep=
}
}
TaskBean包含的"繁重任務"是計算
protectedvoidwork(){
try{
Thread
counter++;
sum+=counter;
}catch(InterruptedExceptione){
setRunning(false);
}
}
status
publicsynchronizedintgetPercent(){
returncounter;
}
如果任務已經啟動
publicsynchronizedbooleanisStarted(){
returnstarted;
}
如果任務已經完成
publicsynchronizedbooleanisCompleted(){
returncounter==
}
如果任務正在運行
publicsynchronizedbooleanisRunning(){
returnrunning;
}
SetRunning()方法由start
publicsynchronizedvoidsetRunning(booleanrunning){
this
if(running)
started=true;
}
任務執行完畢後
publicsynchronizedObjectgetResult(){
if(isCompleted())
returnnewInteger(sum);
else
returnnull;
}
當running標記為true
publicvoidrun(){
try{
setRunning(true);
while(isRunning()&&!isCompleted())
work();
}finally{
setRunning(false);
}
}
二
start
<?xmlversion="
<!DOCTYPEweb
PUBLIC"
"
<web
<welcome
<welcome
</welcome
</web
start
start
下面是start
<%session
<jsp:useBeanid="task"scope="session"
class="test
<%task
<%newThread(task)
<jsp:forwardpage="status
start
現在有兩個線程在並發執行
From:http://tw.wingwit.com/Article/program/Java/JSP/201311/19871.html