java 结束掉一个
查询数据库进程作者:达内 更新时间:2012-10-15 9:42:56 来源:
成都达内 【字号: 大 中 小】 浏览79次
需求:有个小程序,需要查询数据库,查询时间较长,现在想增加一个停止查询功能。
在网上看了下,Thread.stop()方法已经不建议使用了(http://docs.oracle.com/javase/1.5.0/docs/guide/misc/
threadPrimitiveDeprecation.html)。对于周期执行的进程如果想停掉,一般用这种方法:
[java] view plaincopyprint?public
class StoppableTask extends Thread {
private volatile boolean pleaseStop;
public void run() {
while (!pleaseStop) {
// do some stuff...
}
}
public void tellMeToStop() {
pleaseStop = true;
}
}
public class StoppableTask extends Thread {
private volatile boolean pleaseStop;
public void run() {
while (!pleaseStop) {
// do some stuff...
}
}
public void tellMeToStop() {
pleaseStop = true;
}
}对于长时间执行的进程,如果是sleep等等(Thread文档interrupt部分)可以interrupt抛
异常的,就用interrupt。
对于查询数据库,就写了一个类,每次查询的时候都起这么一个定期扫描进程,当想结束掉查询的时候,就thread.interrup(),然后这个定期扫描进程如果
发现还在查询数据库没有查询完成,会调用statement.
cancel(),然后那个正在查询的进程会抛一个interrupt类似的异常(理论可以,下面还没来得及测试)。
[java] view plaincopyprint?package util;
import java.sql.Statement;
import org.apache.log4j.Logger;
public class ThreadInterruptMonitor extends Thread {
private static transient Logger logger = Logger.getLogger(ThreadInterruptMonitor.class);
private Thread thread;
private Statement stmt;
private Integer checkInterval = 1000;
public ThreadInterruptMonitor(Thread thread, Statement stmt) {
this.thread = thread;
this.stmt = stmt;
}
public ThreadInterruptMonitor(Thread thread, Statement stmt, Integer checkInterval) {
this.thread = thread;
this.stmt = stmt;
this.checkInterval = checkInterval;
}
@Override
public void run() {
try {
while (true) {
if (stmt.isClosed()) {
return;
}
if (thread.isInterrupted()) {
stmt.cancel();
return;
}
Thread.sleep(checkInterval);
}
} catch (Exception e) {
logger.error("ThreadInterruptMonitor", e);
}
}
}
举个简单的
例子
public class Tasks {
OracleStatement state;
...
public Type querySql() {
...
}
public boolean cancelSql() {
// 需要加一些
同步逻辑
if ( state != null )
state.cancel();
}
}