Java how to stop threads

So I create a thread

Thread personThread = new Thread(Person); personThread.start(); /** Now to stop it **/ personThread.stop(); 

The problem is that when I try to compile, I get: warning: [deprecation] stop() in Thread has been deprecated . As I understand it, this method is no longer used. How can I completely stop a thread unrelated to it?

+4
source share
3 answers

You must interrupt the flow, which is a gentle way of asking him to stop.

Shameless copy:

 final Thread thread = new Thread(someRunnable); thread.start(); 

Instead of stop() calling interrupt() :

 thread.interrupt(); 

And handle the interrupt manually in the thread:

 while(!Thread.currentThread().isInterrupted()){ try{ Thread.sleep(10); } catch(InterruptedException e){ Thread.currentThread().interrupt(); } 
+5
source

Here's a page on how to: Stop a thread or task

... This article talks about some of the prerequisites for stopping threads and the proposed alternatives and discusses why interrupt () is the answer. It also discusses interrupting I / O locks and what else the programmer needs to ensure that their threads and tasks are suspended.

Regarding Why are Thread.stop, Thread.suspend, Thread.resume and Runtime.runFinalizersOnExit Deprecated? (Related in previous article)

Because it is inherently unsafe. Stopping a thread causes it to unlock all monitors that it has blocked ... This behavior can be subtle and difficult to detect ... the user does not know that his program may be corrupted. Corruption may occur at any time after actual damage, even on hours or days in the future.

+4
source

The correct way to stop the thread is to call the interrupt() method on it and check if the thread was interrupted periodically during execution.

+4
source

Source: https://habr.com/ru/post/1386869/


All Articles