Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/multithreading/4.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 线程停止列表_Java_Multithreading_Swing_Java Threads - Fatal编程技术网

Java 线程停止列表

Java 线程停止列表,java,multithreading,swing,java-threads,Java,Multithreading,Swing,Java Threads,我有一个线程数组列表,如果从GUI中按下取消按钮,我想停止列表中的所有线程。有没有办法阻止所有这些线程 List<Thread> threads = new ArrayList<>(); EncryptThread encryptThread = null; for(int j=0;j<fileEncrytionList.size();j++){ encryptThread = new EncryptThread(); encryptThread.s

我有一个线程数组列表,如果从GUI中按下取消按钮,我想停止列表中的所有线程。有没有办法阻止所有这些线程

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
List threads=new ArrayList();
EncryptThread EncryptThread=null;

对于(int j=0;j线程取消在Java中是一项协作任务-需要对线程进行编程以响应某种取消信号。最常用的两种方法是:

  • 中断。有一种方法是大多数对取消敏感的JDK方法所使用的。例如,大多数阻塞方法都会检测到中断。是否见过
    InterruptedException
    ,例如从
    Thread.sleep()
    ?就是这样
  • 方法是阻塞的,可能是长时间运行的,并且是可取消的。如果线程在睡眠时被中断,它将唤醒并抛出
    InterruptedException

    当接收到中断信号时,任务应该停止它正在做的事情,并抛出一个
    InterruptedException
    ,您可以在上层捕捉到它,按照“关机,再见”的行记录一些内容,理想情况下重新中断线程并让它停止。如果您已将一些阻塞任务编程到线程中,则检查
    thread.interrupted()
    是处理取消的一种方法

  • 一个标志。如果你的线程在一个循环中再次执行一些重复工作,那么该循环可以更改为:

    private volatile boolean shouldContinue=true;
    @凌驾
    公开募捐{
    while(应该继续){
    //…做工作。
    }
    }
    公共图书馆{
    shouldContinue=false;
    }
    
    …或者类似的东西

  • 一般的信息是-你的可运行程序需要知道它们是可取消的,并且它们需要合作。无论你做什么,都不要调用该方法