我做了一个抽象基类用于执行任务。通过Timer实现的。。源代码如下。。
有两个实现类,结构完全一样,但是放在不同的地方就不可以控制了。
例如。将声明放在UI界面里。线程可以控制setStatus(status)
如放在Listener里就不能控制线程??奇怪??import java.util.Hashtable;
import java.util.Timer;
import java.util.TimerTask;public abstract class AbstractThread {
protected int status = -1;// 0 启动 1 暂停 2 停止 protected Timer timer; protected Hashtable param;// 参数 protected ThreadTask task;// 任务 protected int seconds = 2;// 单位秒。。时间间隔 public AbstractThread() {

init();
} abstract protected void init();// 该函数主要是执行初始化操作。例如获得正在启动前进程的状态。 public synchronized int getStatus() {
return status;
} public void setSeconds(int seconds) {
this.seconds = seconds;
} public int getSeconds() {
return this.seconds;
} public void addParam(String key, Object value) {
if (param == null)
param = new Hashtable();
if (param.containsKey(key))
param.remove(key);
param.put(key, value);
} public void clearParam() {
param.clear();
} public void setStatus(int i) {

if (i == status)
return;
System.out.println("setStatus("+i+")");
if (i == 0) {
this.status = 0;

if (timer == null) {
timer = new Timer();
if (task == null) {
task = new ThreadTask();
timer.schedule(task, 0,seconds*1000);
}

}
try {
doStart();
} catch (Exception e) {
}
} else if (i == 1) {
try {
this.status = 1;
doPause();

} catch (Exception e) {

} } else {
try {
this.status = 2;
if (timer != null)
timer.cancel();
timer = null;
task = null;
doStop();

} catch (Exception e) {
}
}

} abstract protected void doStart(); abstract protected void doPause(); abstract protected void doStop(); abstract protected void doTask(); public class ThreadTask extends TimerTask {
public void run() {
if (getStatus() == 0)// 如果在启动状态
doTask();// 执行任务
}
} protected void finalize() {
if (timer != null)
timer.cancel();
timer = null;
task = null;
}
}实现类
public class ShowDataTask extends AbstractThread {
private Vector data;
private String name;
private Task task;
private Table table;
public ShowDataTask(String name,Table table){
super();
this.name=name;
this.table=table;
}

protected void init() { } protected void doStart() { } protected void doPause() { } protected void doStop() { }

protected void doTask() {

if(status!=0) return ;
if(task==null)
task = new Task();
TableData tableData = DataFactory.getTableData(name);
if(tableData==null) return;
data = tableData.getData(param);
if(data==null ) return;
MainFrame.display.asyncExec(task);

}
public class Task implements Runnable{

public void run() {
if(data==null||table==null) return;
int i,max=table.getItems().length;
TableItem item;
for(i=0;i<data.size();i++){
if(i<max) //如果table中有Item;避免重新生成Item,减少内存占用
item = table.getItem(i);
else
item = new TableItem(table,0);
item.setText((String[])data.get(i));
}
if(i<max){
table.remove(i,max);
}
}

}}