现在有个很急的问题,我发现我启动了我写的小程序后,我无法停止它public class ProtectThread extends Thread{
private static final Log log = LogFactory.getLog(ProtectThread.class);
private List<MyTimer> t = new ArrayList<MyTimer>();
@Override
public void run() {
MyTimer t1 = new MyTimer("refreshCache,refreshMongP,refreshMongG,refreshMongC,recStat,ConStat",new Date(),1000*60);
t.add(t1);
while(true){
try {
//new DataSupport().doSendBulk();
Thread.sleep(1000);
System.out.println("1");
} catch (Exception e) {
log.error(e);
}
}
}
public void thisStop(){
for (int i = 0 ; i< t.size() ; i++){
t.get(i).stop();
}
this.interrupt();
}
}这是它的主要线程,但我一旦从命令行启动,我就发现我没有方法停止它
private static final Log log = LogFactory.getLog(ProtectThread.class);
private List<MyTimer> t = new ArrayList<MyTimer>();
@Override
public void run() {
MyTimer t1 = new MyTimer("refreshCache,refreshMongP,refreshMongG,refreshMongC,recStat,ConStat",new Date(),1000*60);
t.add(t1);
while(true){
try {
//new DataSupport().doSendBulk();
Thread.sleep(1000);
System.out.println("1");
} catch (Exception e) {
log.error(e);
}
}
}
public void thisStop(){
for (int i = 0 ; i< t.size() ; i++){
t.get(i).stop();
}
this.interrupt();
}
}这是它的主要线程,但我一旦从命令行启动,我就发现我没有方法停止它
try {
//new DataSupport().doSendBulk();
Thread.sleep(1000);
System.out.println("1");
} catch (Exception e) {
log.error(e);
}
}这段貌似死循环了
while(true)
改成
while(flag)
flag 是一个boolean值,可以通过方法调用来设置成false
这样的方法来终止ProtectThread线程。
try {
//new DataSupport().doSendBulk();
Thread.sleep(1000);
System.out.println("1");
} catch (Exception e) {
log.error(e);
}
}
死循环,参照2楼的,在你循环执行中有方法或者其他的线程中能改变flag中的值
interrupt只适用于阻塞时的停止,它只是抛异常,可以在循环内捕获后更改信号量。
2 线程停止工作的前提
2-1 当前sleep的线程唤醒 ,thread.interrupt
2-2 停止循环, while(true) -> break
public static ProtectThread thread = new ProtectThread();
public static void main(String[] args) throws Exception {
thread.start();
}
现在我把这个程序打包成jar文件后在cmd中启动,无法停止,你们说的设定flag值已经试过无用!!!!!!!!!!!!!!!!!!!!!
现在,我再次请问,应该如何从命令行执行命令调用什么样的java方法才可以停止我启动的这个线程,具体的java代码应该怎么编写,或者是应该用什么java方法来停止我启动的这个线程