Reputation: 103
I have thread which contains a loop
while(isRunning){
}
isRunning
is a Boolean variable with the value true
, when some clicks on a button it gets false
and so it leaves the loop and the run()
function of the thread.
I want to create another button that on click it will reenter the run()
function.
I am not sure if when I leave the run()
function the thread dies or just stops.
I have tried using thread.run()
but it didnt work.
Also I have looked for an answer in other's people questins about this matter but nothing seemed to help me. Thanks for the help
Upvotes: 0
Views: 40
Reputation: 15146
When a thread is finish processing it's code, There's no way of restarting it. You can either:
Create a new thread and pass the Runnable
to that thread.
If you need to use that run()
method often, use an Executor
. You can use Executors.newSingleThreadExecutor()
, which will supply you with a worker thread. (Reusable thread).
class Example {
static ExecutorService executor = Executors.newSingleThreadExecutor();
static Runnable run = new Runnable() {
public void run() {
}
};
public static void main(String[] args) {
//anytime you wanna run that code..
executor.execute(run);
}
}
Upvotes: 1
Reputation: 474
If your thread runs to its end, it stops. It will remain there for you to collect its return status until the thread is cleaned up.
To restart within the same thread, you need an extra control flow. For instance:
while (restarted) {
while (isRunning) {
}
// Wait for a restart or end click
}
That is what so called worker threads in a thread pool do, which are intended for maximum performance.
But logically, you will probably simply want to create a new thread object and start that one.
new Thread(p).start();
Upvotes: 0
Reputation: 1074
Please read through java concurrency tutorial. http://docs.oracle.com/javase/tutorial/essential/concurrency/
Just Maybe, guarded blocks might be useful for your case but your case is a little vague to recommend anything specific. http://docs.oracle.com/javase/tutorial/essential/concurrency/guardmeth.html
Upvotes: 0