0

I use this code for find all runnable thread

And i want terminate this thread but my code not working

How i can ?

for (Thread t: Thread.getAllStackTraces().keySet()) {
    if (t.getState() == Thread.State.RUNNABLE) {
        t.stop();
        //Thread.interrupted();
    }
}
Halvor Holsten Strand
  • 19,829
  • 17
  • 83
  • 99
Mohammad
  • 197
  • 3
  • 12
  • Is` t.getState()` returning a valid value? Try just outputting that to make sure that you are retrieving any threads at all. – greg_diesel Mar 03 '15 at 18:41
  • Yes this code return all thread – Mohammad Mar 03 '15 at 18:51
  • Please see this thread on implementing your own proper stop method. http://stackoverflow.com/questions/10630737/how-to-stop-a-thread-created-by-implementing-runnable-interface – greg_diesel Mar 03 '15 at 20:38

1 Answers1

0

I would create a separate class that implements Runnable and do this:

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; }
}

So to create the Thread, you would do

GameLoopThread gameLoopThread = new GameLoopThread(this);
gameLoopThread.setRunning(true);
Thread t = new Thread(gameLoopThread);

And when you want to stop it:

gameLoopThread.setRunning(false);

Basically it's a custom Thread that has a way to stop it.

IntegralOfTan
  • 640
  • 6
  • 18
  • sorry, i don't understand what you're asking – IntegralOfTan Mar 04 '15 at 01:40
  • gameLoopThread.setRunning(false) stops the thread. Also, gameLoopThread is NOT a thread, it is a Runnable. You still make a thread the regular way, but with gameLoopThread as the parameter (above) – IntegralOfTan Mar 04 '15 at 01:40