Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop a runnable in a separate Thread

Hey there i currently have a problem with my android app. I´m starting an extra thread via implementing the Excecutor Interface:

class Flasher implements Executor {
    Thread t;
   public void execute(Runnable r) {
     t = new Thread(r){
     };
     t.start();
   }
 }

I start my Runnable like this:

flasherThread.execute(flashRunnable);

but how can i stop it?

like image 578
TobiasPC Avatar asked Dec 26 '22 12:12

TobiasPC


1 Answers

Ok, this is just the very basic threading 101, but let there be another example:

Old-school threading:

class MyTask implements Runnable {
    public volatile boolean doTerminate;

    public void run() {
        while ( ! doTerminate ) {
            // do some work, like:
            on();
            Thread.sleep(1000);
            off();
            Thread.sleep(1000);
        }
    }
}

then

MyTask task = new MyTask();

Thread thread = new Thread( task );

thread.start();

// let task run for a while...

task.doTerminate = true;

// wait for task/thread to terminate:
thread.join();
// task and thread finished executing

Edit:

Just stumbled upon this very informative Article about how to stop threads.

like image 128
JimmyB Avatar answered Jan 03 '23 00:01

JimmyB