Java 线程停止列表
我有一个线程数组列表,如果从GUI中按下取消按钮,我想停止列表中的所有线程。有没有办法阻止所有这些线程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
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;
}
…或者类似的东西