Reputation: 2073
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.
Upvotes: 3
Views: 4411
Reputation:
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.
Upvotes: 9
Reputation: 15698
In order to stop a thread ,first create a thread like this
Thread thread = new Thread(run);
and in order to start the thread call
thread.start();
The start method will call run
method but if you call run()
method directly then no new thread will be created and the code will be executed in the existing thread. In order to stop the method you can use interrupt
Upvotes: 1
Reputation: 11307
The simplest thing you normally do is to add a volatile boolean field to the runnable that is set by a different thread.
In your case you might perhaps use an AtomicBoolean instead of a volatile field and capture that in the closure. Once the closure is created, you can use this AtomicBoolean to stop.
Upvotes: 1