我使用此代码查找所有可运行的线程
我想终止这个帖子,但我的代码不能正常工作
我怎么样?
for (Thread t: Thread.getAllStackTraces().keySet()) {
if (t.getState() == Thread.State.RUNNABLE) {
t.stop();
//Thread.interrupted();
}
}
答案 0 :(得分:0)
我会创建一个单独的类来实现Runnable并执行此操作:
public class GameLoopThread implements Runnable {
private GameView view;
private boolean running = false;
private SurfaceHolder surfaceHolder;
public GameLoopThread(GameView view) {
this.view = view;
surfaceHolder = view.getHolder();
}
@Override
public void run() {
Canvas c;
while (running) {
c = null;
try {
c = this.surfaceHolder.lockCanvas();
synchronized (surfaceHolder) {
//draw your stuff
}
} finally {
if (c != null) {
surfaceHolder.unlockCanvasAndPost(c);
}
}
}
}
public void setRunning(boolean run) { running = run; }
}
所以要创建线程,你会做
GameLoopThread gameLoopThread = new GameLoopThread(this);
gameLoopThread.setRunning(true);
Thread t = new Thread(gameLoopThread);
当你想要阻止它时:
gameLoopThread.setRunning(false);
基本上它是一个可以阻止它的自定义线程。