線程回調方式我們已經在"
使用回調和線程處理一個耗時響應過程"文中進行了講述,但是有些情況下用戶希望在指定時間內返回一個結果,免得無休止的等待下去.這時我們需要使用"限時線程回調方式",它在原有線程回調的基礎上加上了一個Timer以計算消耗的時間,如果時間期限到了任務還沒有執行完的話即中斷線程,示例代碼如下:
package com.sitinspring;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.Timer;


/** *//**
* 定時回調線程類
*
* @author sitinspring(junglesong@gmail.com)
*
* @date 2007-11-6
*/

public class TimedCallBackThread implements Runnable
{
// 一秒的毫秒數常量
private final static int ONE_SECOND = 1000;

// 限制時間,以秒為單位
private final int waitTime;

// 已經流逝的時間
private int passedTime;

private Timer timer;

private Thread thread;

private MvcTcModel model;

private MvcTcView view;


public TimedCallBackThread(MvcTcModel model, MvcTcView view, int waitTime)
{
this.model = model;
this.view = view;
this.waitTime = waitTime;
this.passedTime = 0;

// 創建并啟動定時器

timer = new Timer(ONE_SECOND, new ActionListener()
{

public void actionPerformed(ActionEvent evt)
{
timeListener();
}
});
timer.start();

// 創建并啟動線程來完成任務
thread = new Thread(this);
thread.start();
}


private void timeListener()
{
passedTime++;

// 動態顯示狀態
int modSeed = passedTime % 3;

if (modSeed == 0)
{
view.getLabel2().setText("響應中");

} else if (modSeed == 1)
{
view.getLabel2().setText("響應中..");

} else if (modSeed == 2)
{
view.getLabel2().setText("響應中
.");
}

// 如果流逝時間大于規定時間則中斷線程

if (passedTime > waitTime)
{
passedTime = waitTime;
thread.interrupt();
}
}


public void run()
{

while (passedTime < waitTime)
{

try
{
Thread.sleep(10000);// 模擬一個耗時相應過程
timer.stop();// 任務完成,停止Timer

view.getLabel2().setText(model.getText2());

} catch (InterruptedException ex)
{
timer.stop();// 線程中斷,停止Timer
view.getLabel2().setText("在指定時間內未響應");

} catch (Exception ex)
{
ex.printStackTrace();
}

return;
}
}
}
執行效果如下:

本文代碼下載(點擊第二個按鈕):
http://www.tkk7.com/Files/sitinspring/TimedThreadCallBack20071106194506.rar