How can you stop a Thread? - Cracking the Java Coding Interview

preview_player
Показать описание
Cracking the #Java #Coding #Interview - Question 75: How can you stop a Thread?
Рекомендации по теме
Комментарии
Автор

Stopping threads is actually super simple. Just press the power button

Jackson_Zheng
Автор

If you have to manage your own threads, you can use the Thread.interrupt() method and gracefully break out of the run() method once returns true or you catch an InterruptedException (e.g. from a call to Thread.sleep()).

jay_sensz
Автор

I’m suprised you didn’t mention the iterrupt() method. Great explanation though as usual

ahmedjaad
Автор

Wow, thanks, I didn’t know that, keep up the good videos, thanks a lot!!!
Though I am android developer, your videos helps me, since kotlin is built on java.
And apparently understanding java makes kotlin even easier to reason about

SoyAmurita
Автор

just recently I had to use threads for a problem and using the executor service was getting in the way and I had to remove it. the problem was related to the notification about "work done"/ thread finished (in the context of a shutdown lifecycle) - that old Future api is bad (just as many other oldish java apis).
I think executor service works ok when a, simple queue is required.
I'll no longer use it for infinite loops / long running tasks
and no, #stop () is not being called :)... even if handling interrupt exception is not trivial (you could make a video on that)

madskaddie
Автор

Devide by zero and catch the exception to stop the thread.

boolhak
Автор

I am curious, how does the ExecutorService manage threads that currently aren't doing anything. Does it shut them down and launch new ones when new tasks appear? or are they stuck in some kind of loop waiting?

diluconeal
Автор

There is a ton of cases where thread interruptions are needed. Especially when you are working with different hardware that can only be used in 1 thread at the same time.
OpenGL comes to a example.

A example I am using is:
I have a main thread executor that can only run for about 2-3 milliseconds and then it HAS TO STOP. The interrupt api basically allows me to cancel the task and make sure that the task knows where to continue when it is next.

Why does it have to stop.
With games/framerate relevant data you only have so many milliseconds before it kills the experience.

Speiger
Автор

I am using Threads itself, because i have a Server and a client application, where the Server has for each Client a ClientHandler which is a thread. How could i make a ExecuterServices when i don't know how many Clients connection to the Server

Kolbenik
Автор

Thanks José for your useful content. Please keep on.
Meme en août la passion de java est là ❤.

Talaria.School
Автор

so thread.interrupt() doesnt stop/terminate the thread?

NivedSuresh-eh