"Hello, Amigo! Here's an interesting question that you've either already had or you will soon. How do you stop a running thread?"

Let's say the user tells the program to «download a file from the Internet». The main thread creates a separate child thread for this job, and passes it an object whose run method contains all the necessary actions to download the file.

But suddenly the user changes his mind. He doesn't want to download the file. How do we cancel a job and stop the thread?

"Yes, tell me how?"

"We can't. That's the most common and most correct answer. You cannot stop a thread. Only it can stop itself."

But you can send a signal to a thread, in some way telling it that the work no longer needs to be performed and that it should terminate. Just as the main thread terminates by returning from the main method, a child thread terminates by returning from the run method.

"What's the best way to do that?"

"You can add some variable, such as a boolean. If it is true, the thread runs. If it is false , the thread should terminate. Like this, for example:"

Code Description
class Clock implements Runnable
{
public void run()
{
while (true)
{
Thread.sleep(1000);
System.out.println("Tick");

if (!ClockManager.isClockRun)
return;
}
}
}

The Clock class writes «Tick» to the console once a second forever

If ClockManager.isClockRun is false, the run method ends.

class ClockManager
{
public static boolean isClockRun = true;
public static void main(String[] args)
{
Clock clock = new Clock();
Thread clockThread = new Thread(clock);
clockThread.start();

Thread.sleep(10000);
isClockRun = false;
}

}
The main thread starts a child thread (clock) that should run forever

Wait 10 seconds and give the clock a signal to end.

The main thread completes its work.

The clock thread ends its work.

"What if we have several threads, then what?"

"It's best to have such a variable for each thread. It's most convenient to add it directly to the class. You could add a boolean isRun variable there. However, it is better to add a boolean isCancel variable that becomes true if the task is canceled."

Code Description
class Clock implements Runnable
{
private boolean isCancel = false;

public void cancel()
{
this.isCancel = true;
}

public void run()
{
while (!isCancel)
{
Thread.sleep(1000);
System.out.println("Tick");
}
}
}
The Clock class writes the word «Tick» to the console once a second as long as isCancel is false.

When isCancel becomes true, the run method terminates.

public static void main(String[] args)
{
Clock clock = new Clock();
Thread clockThread = new Thread(clock);
clockThread.start();

Thread.sleep(10000);
clock.cancel();
}
The main thread starts a child thread (clock) that should run forever

Wait 10 seconds and cancel the task by calling the cancel method.

The main thread completes its work.

The clock thread ends its work.

"I'll keep this in mind. Thanks, Ellie."