Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Stop List of Threads

I have an array list of Threads and I want to stop all threads in the list if the cancel button pressed from GUI. Is there any way to stop all these threads?

List<Thread> threads = new ArrayList<>();
EncryptThread encryptThread = null;
for(int j=0;j<fileEncrytionList.size();j++){
    encryptThread = new EncryptThread();
    encryptThread.setFilePath(fileEncrytionList.get(j));
    encryptThread.setOutPutFile(fileName);
    Thread t = new Thread(encryptThread);
    t.start();
    threads.add(t); 
}

if(cancel button pressed) // stop all threads from arraylist
like image 637
tyb9900 Avatar asked Dec 31 '22 16:12

tyb9900


1 Answers

Thread cancellation is a cooperative task in Java - the threads need to be programmed to respond to some kind of a cancellation signal. The two most common ways to do this are:

  1. Interruption. There is a Thread#interrupt() method which is what most JDK methods sensitive to cancellation use. E.g. most blocking methods will detect interruption. Ever seen an InterruptedException, e.g. from Thread.sleep()? That's it! The sleep() method is blocking, potentially long-running, and cancellable. If the thread is interrupted while sleeping, it will wake up and throw an InterruptedException.

    Upon receiving an interrupt signal, a task should stop what it's doing and throw an InterruptedException which you can catch in the upper layers, log something along the lines of "Shutting down, bye!", ideally reinterrupt the thread and let it die. If you've programmed some blocking tasks into your threads, checking Thread.interrupted() is one way to handle cancellation.

  2. A flag. If your thread is doing some repetitive work all over again in a loop, that loop can be changed to:

    private volatile boolean shouldContinue = true;
    
    @Override
    public void run() {
        while (shouldContinue) {
            // ...do work.
        }
    }
    
    public void cancelPlease() {
        shouldContinue = false;
    }
    

    ...or something along those lines.

The general message is - your runnables need to know they're cancellable, and they need to cooperate. Whatever you do, do NOT call the Thread#stop() method.

like image 69
Petr Janeček Avatar answered Jan 14 '23 21:01

Petr Janeček