简体   繁体   English

Java-如何中断繁忙的线程

[英]Java - how to interrupt a busy thread

I am trying to interrupt a thread that is running AES encryption on a file. 我试图中断正在文件上运行AES加密的线程。 That can take a while, so far I have come up with this. 这可能需要一段时间,到目前为止,我已经提出了这个建议。

This body is inside button activate event. 该主体位于按钮激活事件内部。 When the user clicks the button again (else clause). 当用户再次单击按钮时(else子句)。 The thread should be interrupted, but I would be happier if I could stop the thread completely. 线程应该被打断,但是如果我可以完全停止线程的话,我会更快乐。 But that is deprecated. 但这已被弃用。

Anyway, the thread ignores the .interrupt() and continues to execute the aes256File. 无论如何,线程将忽略.interrupt()并继续执行aes256File。 It does raise the fileEncryptThread.isInterrupted() flag, but from cpu usage I can see it still continues to crunch the file. 它的确提高了fileEncryptThread.isInterrupted()标志,但是从CPU的使用情况来看,它仍然继续处理文件。

I have read the guide on safe stopping of threads, but I have no desire to completely redesign my already slow AES implementation to be checking for out of class interrupts flags... 我已经阅读了有关安全停止线程的指南,但是我不想完全重新设计我已经很慢的AES实现以检查类外中断标志...

    fileEncryptThread = new FileThread() // new thread please
    {
        @Override
        public void run()
        {
            String result = "";
            result = MyCrypto.aes256File(enInPath,
                                         enOutPath, 
                                         charsToString(passT.getPassword()),
                                         sec);
            if (!"".equals(result)) // error handling
            {
                JOptionPane.showMessageDialog(null,result);
            }
        }
    };
    fileEncryptThread.start();
  }
  else // if stop clicked
  {
      fileEncryptThread.interrupt();

In order to effectively interrupt a thread, that thread has to be written in an interruptible way. 为了有效地中断线程,必须以一种可中断的方式写入该线程。 That is, check the 也就是说,检查

Thread.currentThread().isInterrupted() Thread.currentThread()。isInterrupted()

boolean and act thereupon. 布尔值,然后采取行动。

In your app, you should verify that 在您的应用中,您应验证

result = MyCrypto.aes256File(enInPath, enOutPath, charsToString(passT.getPassword()), sec); 结果= MyCrypto.aes256File(enInPath,enOutPath,charsToString(passT.getPassword()),秒);

acts in such a manner (if its a 3rd party library, it should be javadoc'ed). 以这种方式操作(如果它是第三方库,则应使用javadoc'ed)。 If it's not interruptible, you'd choose another implementation for encryption. 如果它不是不可中断的,则可以选择另一种实现方式进行加密。

AFAIK, the only safe way for a thread to terminate is to return from the "main"-method of the thread (usually run() in Runnable or Thread). AFAIK,线程终止的唯一安全方法是从线程的“主”方法(通常是Runnable或Thread中的run())返回。 You could for example use a while(<some class member boolean>) -loop inside your MyCrypto.aes256File -method and set the boolean to false so the thread will fall out of the loop and exit returning a value indicating that the process was not completed. 例如,您可以在MyCrypto.aes256File -method中使用while(<some class member boolean>) -loop并将boolean设置为false,这样线程将退出循环并退出并返回一个值,该值指示进程未完成。

One other approach that may be possible, (I don't know the AES algorithm well enough), would be split up the file reading from the encryption. 另一种可能的方法(我不太了解AES算法)将从加密中读取文件分开。 A read thread would fill large-ish buffers from the file and queue them to the encryption thread. 读取线程将填充文件中较大的缓冲区,并将它们排队到加密线程中。 The encryption thread would process the buffers and queue the 'used' ones back to the reader thread. 加密线程将处理缓冲区,并将“已使用”的缓冲区排队返回给读取器线程。 This allows both easy stopping of both threads while also probably improving performance, especially on multi-core machines, by moving I/O waits out of the encrypter. 通过将I / O等待移出加密器,这既可以轻松停止两个线程,又可以提高性能,尤其是在多核计算机上。 The encryption thread would probably never have to wait for a disk read - a temporary wait by the reader thread for a disk head move would not matter if the encryption thread had enough buffers to go at in the queue, (even on a single-core machine). 加密线程可能永远不必等待磁盘读取-如果加密线程在队列中有足够的缓冲区(即使在单核上),则读取器线程临时等待磁盘磁头移动也无关紧要。机)。 The fixed number of buffers and the two (blocking, thread-safe), queues provide flow-control should the reader thread get ahead of the encrypter. 固定数量的缓冲区和两个(阻塞,线程安全)队列可在读取器线程领先加密器之前提供流控制。

The actual stopping mechanism then becomes somewhat trivial. 这样,实际的停止机制就变得微不足道了。 The gain in avoiding disk latency would overwhelm the time wasted checking a flag occasionally, eg. 避免磁盘等待时间的收益将使偶尔检查标志所浪费的时间不堪重负。 just before going to the queue for the next buffer. 就在进入下一个缓冲区的队列之前。

Queueing buffers then also allows the possibility of adding sequence numbers to the buffers and so allowing all cores to work on the encryption. 然后,对缓冲区进行排队还可以将序列号添加到缓冲区中,从而允许所有内核进行加密。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM