I am trying to interrupt thread that is working long. In my example inside run() method appear lots of different method with take quite a lot of time (e.g writing into database). I would like to stop (kill) that thread from another one. I have seen solution like:
while(!Thread.currentThread().isInterrupted()){
try{
// do stuff
}catch(InterruptedException e){
Thread.currentThread().interrupt(); // propagate interrupt
}
}
but I've got no while loop inside my code. Can anyone help me to deal with that?
Here's the code:
public void run() //parsingThread
{
try {
for(int index=0; index<tasks.size();)
{ //do sth
if(Thread.currentThread().isInterrupted()==true)
{
System.out.println("Parsing ABORTED");
Thread.currentThread().interrupt();
}
}
for(int index=0; index<1000;index++)
{ //do sth
if(Thread.currentThread().isInterrupted()==true)
{
System.out.println("Parsing ABORTED");
Thread.currentThread().interrupt();
}
}}
If your long-running database calls don't respond to interrupts, then you're basically out of luck, and need to resort to workarounds if you for instance want a responsive user interface.
One way is to run the database methods in a background thread and periodically check for stop-early conditions (such as interruptions) in the main thread. When such condition is discovered, you simply abandon the background thread and ignore any future results from it.
If possible, you could try to split up the long running task into multiple smaller tasks, and check for interrupts in between.
(Some people may point you to
Thread.stop
, but that method has been deprecated for very good reasons.)Official documentation (which in part answers the question you posted too):
Why Are
Thread.stop
,Thread.suspend
,Thread.resume
andRuntime.runFinalizersOnExit
Deprecated?Regarding your code.
If
//do sth
is a long running task, theThread.currentThread().isInterrupted()==true
check is never executed.I've copied your program and executed it locally, and the
"Parsing ABORTED"
is being printed for me.