Search code examples
javamultithreadingrunnable

How to stop a java 8 lambda-runnable-thread


I would like to stop this thread:

Runnable run = () -> { while(true)[...]; };
run.run();

But there is no run.stop() method.

Please suggest either an other as short as possible method to start and stop a thread or a method to stop this running... thing.


Solution

  • Runnable.run() does not create a thread. You're invoking the run() method in your current thread. To create a thread you need to do just that: create and start a thread:

    Thread t = new Thread(run);
    t.start();
    

    Then later on you can invoke

    t.interrupt();
    

    Please read the javadocs on Thread.interrupt() on how to structure your run() method to be interruptable.