春风博客

春天里,百花香...

导航

<2007年11月>
28293031123
45678910
11121314151617
18192021222324
2526272829301
2345678

统计

公告

MAIL: junglesong@gmail.com
MSN: junglesong_5@hotmail.com

Locations of visitors to this page

常用链接

留言簿(11)

随笔分类(224)

随笔档案(126)

个人软件下载

我的其它博客

我的邻居们

最新随笔

搜索

积分与排名

最新评论

阅读排行榜

评论排行榜

限时线程回调方式的实现

线程回调方式我们已经在"使用回调和线程处理一个耗时响应过程"文中进行了讲述,但是有些情况下用户希望在指定时间内返回一个结果,免得无休止的等待下去.这时我们需要使用"限时线程回调方式",它在原有线程回调的基础上加上了一个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.blogjava.net/Files/sitinspring/TimedThreadCallBack20071106194506.rar

posted on 2007-11-06 12:05 sitinspring 阅读(1126) 评论(0)  编辑  收藏 所属分类: 线程Thread


只有注册用户登录后才能发表评论。


网站导航:
 
sitinspring(http://www.blogjava.net)原创,转载请注明出处.