现在有个很急的问题,我发现我启动了我写的小程序后,我无法停止它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();
}
}这是它的主要线程,但我一旦从命令行启动,我就发现我没有方法停止它

解决方案 »

  1.   

    while(true){
                try {
                    //new DataSupport().doSendBulk();
                    Thread.sleep(1000);
                    System.out.println("1");
                } catch (Exception e) {
                    log.error(e);
                }
            }这段貌似死循环了
      

  2.   

    不太懂,要是我的话,就把
    while(true)
    改成
    while(flag)
    flag 是一个boolean值,可以通过方法调用来设置成false
    这样的方法来终止ProtectThread线程。
      

  3.   

    while(true){
                try {
                    //new DataSupport().doSendBulk();
                    Thread.sleep(1000);
                    System.out.println("1");
                } catch (Exception e) {
                    log.error(e);
                }
            }
    死循环,参照2楼的,在你循环执行中有方法或者其他的线程中能改变flag中的值
      

  4.   

    stop已经不推荐使用了,应该在线程中使用信号量来控制。
    interrupt只适用于阻塞时的停止,它只是抛异常,可以在循环内捕获后更改信号量。
      

  5.   

    1 如果是控制台的话,stop 直接使用system.exit(-1)
    2 线程停止工作的前提 
     2-1 当前sleep的线程唤醒 ,thread.interrupt
     2-2 停止循环, while(true) -> break
      

  6.   

    先让我们搞清楚一点,现在main方法是这样
    public static ProtectThread thread = new ProtectThread();
    public static void main(String[] args) throws Exception {
    thread.start();
    }
    现在我把这个程序打包成jar文件后在cmd中启动,无法停止,你们说的设定flag值已经试过无用!!!!!!!!!!!!!!!!!!!!!
    现在,我再次请问,应该如何从命令行执行命令调用什么样的java方法才可以停止我启动的这个线程,具体的java代码应该怎么编写,或者是应该用什么java方法来停止我启动的这个线程
      

  7.   

    再补充一点,不能杀死java虚拟机
      

  8.   

    我现在是main方法执行完成了一次了!!!,此时我应该如何查找到我已经开始执行的线程并终止它