我有一个方法,应该中断一个线程,但它不是。我是否需要始终检查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操作,我现在的代码添加布尔变量“终止”,我只是想找到一个更好的解决方案: (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);
}
}
}
}
}
和fullrotate方法:
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();
}
1)*“我怎样才能刚刚终止线程在任何时候?“*你认为你可以实现Java的制造商说他们不能(至少,不安全)? 2)'//在很长一段时间里做很多事情'代码说话比语言更响亮。为了更快地获得更好的帮助,请发布[SSCCE](http://sscce.org/)。 – 2012-04-09 11:10:22
你检查:http://docs.oracle.com/javase/1.5.0/docs/guide/misc/threadPrimitiveDeprecation.html – anuragsn7 2012-04-09 11:28:55