CodeGym /Courses /Java Core /Stopping threads: the unofficial version

Stopping threads: the unofficial version

Java Core
Level 6 , Lesson 8
Available

"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."

Comments (5)
TO VIEW ALL COMMENTS OR TO MAKE A COMMENT,
GO TO FULL VERSION
Michał Pawłowicz Level 18, Polska
17 April 2020
I'd like to ask, why I am obliged by IntellJ to surround the Thread.sleep with try catch, and in these examples there are no try catch blocks. Be my hero, explain it to me, please.
Andrey Level 18, St. Petersburt, Russian Federation
22 April 2020
I think it's for the simplicity of reading this code examples because besides of try\catch exceptions can be carried out to methods throws. Details about InterruptedException IntellJ offers are on the next page of the course.
Daniel Walbolt Level 22, Waterville, United States
9 July 2020
The sleep method for every Thread object requires a try catch statement in IntelliJ because it has the possibility of sending an InterruptedException. An exception where the thread is currently doing some type of work and then at the same time is told to stop working. In most of our cases, any thread won't be doing work that takes more than 5 milliseconds before coming back to the run method (work is considered to be performing an outside method) to receive the instruction to sleep. Of course, you don't HAVE to catch the exception, and you can just let the error have the LIKELY possibility of existing (because no one really knows what the Thread is working on at the moment). If an error does exist because the Thread is already doing work, it unwinds the stack and closes the program because of no catch statement. It is basically just safer programming to catch the exception and have the ability to do something else if the Thread can't be stopped.
Sela Level 20, Poland
27 July 2020
just to force us to think how to break the loop if exception is caught
Hoist Level 4, San Diego, United States
13 November 2022
@daniel >>That helps