Java 随时停止线程

Java 随时停止线程,java,multithreading,interrupt,terminate,Java,Multithreading,Interrupt,Terminate,我有一个方法,它应该中断一个线程,但它不是。我是否需要始终检查while方法中中断的线程以停止线程?如何随时终止线程 solverTh = new Thread(new Runnable() { @Override public void run() { while(somethingistrue){ //do lot of stuff here for long time }

我有一个方法,它应该中断一个线程,但它不是。我是否需要始终检查while方法中中断的线程以停止线程?如何随时终止线程

solverTh = new Thread(new Runnable() {
        @Override
        public void run() {
            while(somethingistrue){
                //do lot of stuff here for long time
            }
        }
    });
    solverTh.start(); 
}

public void terminate(){
    if(solverTh != null){
        solverTh.interrupt();
    }
}
好吧,比我认为“很多东西”是无关的,但我会张贴它比。它进行openGL操作,我将布尔变量“terminated”添加到它现在工作的代码中,我只是想找到一个更好的解决方案: (glc是GLCanvas,rotmultiplecube方法旋转3个对象) 不管怎样,我现在已经解决了这个问题,谢谢你的回答

            terminated = false;
            try {
                Thread.sleep(2000);
            } catch (InterruptedException ex) {
                Logger.getLogger(BruteForce.class.getName()).log(Level.SEVERE, null, ex);
            }

            int colorToBeSolved = Statics.RED_BLUE_TABLE[stateToBeSolved];
            System.out.println(stateToBeSolved + "," + colorToBeSolved);
            if(entities[0].getColor() != colorToBeSolved){
                if(terminated) return;
                fullRotate(Statics.FIRST_ROW, Statics.DOWN);
            }
            if(entities[1].getColor() != colorToBeSolved){
                if(terminated) return;
                fullRotate(Statics.SECOND_COL, Statics.RIGHT);
            }
            if(entities[2].getColor() != colorToBeSolved){
                if(terminated) return;
                fullRotate(Statics.THIRD_COL, Statics.RIGHT);
            }
            if(entities[3].getColor() != colorToBeSolved){
                if(terminated) return;
                fullRotate(Statics.SECOND_ROW, Statics.DOWN);
            }
            if(entities[6].getColor() != colorToBeSolved){
                if(terminated) return;
                fullRotate(Statics.THIDR_ROW, Statics.DOWN);
            }

            for(int i = 0; i < 9; ++i){
                int col = i % 3;
                int row = 3 + i/3;
                while(entities[i].getState() != stateToBeSolved){
                    for(int j = 0;j < 2; ++j){
                        if(entities[i].getState() != stateToBeSolved){
                            if(terminated) return;
                            fullRotate(col, Statics.LEFT);
                            if(terminated) return;
                            fullRotate(row, Statics.UP);
                            if(terminated) return;
                            fullRotate(col, Statics.RIGHT);
                            if(terminated) return;
                            fullRotate(row, Statics.DOWN);
                        }
                    }
                    for(int j = 0;j < 2; ++j){
                        if(entities[i].getState() != stateToBeSolved){
                            if(terminated) return;
                            fullRotate(col, Statics.RIGHT);
                            if(terminated) return;
                            fullRotate(row, Statics.UP);
                            if(terminated) return;
                            fullRotate(col, Statics.LEFT);
                            if(terminated) return;
                            fullRotate(row, Statics.DOWN);
                        }
                    }
                }
            }
        }
terminated=false;
试一试{
《睡眠》(2000年);
}捕获(中断异常例外){
Logger.getLogger(BruteForce.class.getName()).log(Level.SEVERE,null,ex);
}
int colorToBeSolved=Statics.RED_BLUE_TABLE[stateToBeSolved];
System.out.println(stateToBeSolved+“,”+colorToBeSolved);
如果(实体[0].getColor()!=colorToBeSolved){
如果(终止)返回;
全旋转(静态。第一行,静态。向下);
}
if(实体[1].getColor()!=colorToBeSolved){
如果(终止)返回;
全旋转(Statics.SECOND_COL,Statics.RIGHT);
}
如果(实体[2].getColor()!=colorToBeSolved){
如果(终止)返回;
全旋转(Statics.THIRD_COL,Statics.RIGHT);
}
if(实体[3].getColor()!=colorToBeSolved){
如果(终止)返回;
全旋转(Statics.SECOND_ROW,Statics.DOWN);
}
如果(实体[6].getColor()!=colorToBeSolved){
如果(终止)返回;
全旋转(Statics.THIDR_行,Statics.DOWN);
}
对于(int i=0;i<9;++i){
int col=i%3;
int row=3+i/3;
while(实体[i].getState()!=stateToBeSolved){
对于(int j=0;j<2;++j){
if(实体[i].getState()!=stateToBeSolved){
如果(终止)返回;
全旋转(列,静态。左);
如果(终止)返回;
全旋转(行,静态向上);
如果(终止)返回;
全旋转(col,Statics.右侧);
如果(终止)返回;
全旋转(行,静态。向下);
}
}
对于(int j=0;j<2;++j){
if(实体[i].getState()!=stateToBeSolved){
如果(终止)返回;
全旋转(col,Statics.右侧);
如果(终止)返回;
全旋转(行,静态向上);
如果(终止)返回;
全旋转(列,静态。左);
如果(终止)返回;
全旋转(行,静态。向下);
}
}
}
}
}
全旋转法:

private void fullRotate(int selectionIndex, int direction){
    for(int i = 0; i < 9; ++i){
        glc.rotMultipleCubeSlow(selectionIndex, direction);
        try {
            Thread.sleep(20);
        } catch (InterruptedException ex) {
            terminate();
        }
    }
    glc.setMovesText(selectionIndex, direction);        
    glc.setMultipleStateAndColorsByTable(selectionIndex, direction);
    glc.isEntitiesRight();
}
private void fullRotate(整数选择索引,整数方向){
对于(int i=0;i<9;++i){
glc.旋转多粒子流(选择指数,方向);
试一试{
睡眠(20);
}捕获(中断异常例外){
终止();
}
}
glc.setMovesText(选择索引、方向);
glc.setMultipleStateAndColorsByTable(选择索引、方向);
glc.isEntitiesRight();
}

中断线程的唯一方法是使其自身退出。由于存在死锁的可能性,甚至没有在Java中实现Strightforward中断。因此,线程代码必须如下所示:

solverTh = new Thread(new Runnable() {
    @Override
    public void run() {
        while(somethingistrue) 
            // Do a little stuff here
        }
    }
});
solverTh.start(); 

somethingistrue
是线程中断的一种信号。

唯一可以可靠地停止一个线程执行另一个线程的是操作系统。因此,选择不多:

1) 向线程发出停止自身的信号。这个方案有点取决于线程在做什么。如果它在另一个处理器上运行,或者阻塞呼叫无法解除阻塞(请注意,可以说服许多阻塞呼叫提前返回),则可能存在问题

“很多东西”在做什么

2) 使用操作系统调用终止线程。这可能是一个可行的选项,具体取决于线程的功能。如果有可能在线程在一个重要资源上持有公共锁时终止线程(例如,它位于MALROCK()的中间,并且内存管理器被锁定),那么你可能会遇到麻烦。您必须确定线程正在做什么,才能以这种方式安全地中止它

3) 使用单独的进程来运行“stuff”。这显然可以正常工作,但通常需要缓慢而痛苦的进程间通信来传递数据和返回结果

4) 设计应用程序,使其不需要终止线程。一些应用程序永远不需要终止任何线程,除非在应用程序关闭时,所以没有问题-操作系统可以停止任何事情。在应用程序运行期间必须“停止”线程,并且该线程正在运行一个长时间的CPU密集型操作,或者被阻塞了一段很长且可能不确定的时间的情况下,另一种常见的方法是通过将线程的优先级设置为“最小/空闲”来“孤立”线程,并让它最终消亡

最糟糕的情况可能是一个线程长时间运行大量内容,使用内存管理器或其他公共锁,可能在一个库中,您不知道它在做什么,不能被钩住并以这样一种方式读取/写入数据,“孤立”它意味着另一个线程无法开始使用数据。那么你真的很笨拙,你可能不得不终止应用程序并重新启动。这是最好的
while(somethingistrue !Thread.currentThread().isInterrupted()){
  //do lot of stuff here for long time
}
private void fullRotate(int selectionIndex, int direction)
       throws InterruptedException{
    for(int i = 0; i < 9; ++i){
        glc.rotMultipleCubeSlow(selectionIndex, direction);
        Thread.yield();
    }
    glc.setMovesText(selectionIndex, direction);        
    glc.setMultipleStateAndColorsByTable(selectionIndex, direction);
    glc.isEntitiesRight();
}
solverTh = new Thread(new Runnable() {
    @Override
    public void run() {
        while(somethingistrue && 
              !Thread.currentThread().isInterrupted()) {
            try {
                //do lot of stuff here for long time
            } catch (InterruptedException ex) {
                // handle stop processing 
            }
        }
    }
});
solverTh.start(); 
        try {
            Thread.sleep(2000);
        } catch (InterruptedException ex) {
            Logger.getLogger(BruteForce.class.getName()).log(Level.SEVERE, null, ex);
        }