我目前有一个线程,当您按下 GUI 上的按钮时就会启动,该线程基本上开始下载文件,但我想实现您可以停止线程,这与 t.suspend( 配合得很好。 );
但它已被弃用,所以我尝试使用 t.wait();
和 t.notify();
,这样做的问题是每次我尝试暂停等待时,都会抛出异常“线程“AWT-EventQueue-0”java.lang.IllegalMonitorStateException 中的异常”。
开始下载按钮:
t = new TestTread();
t.start();
暂停:
try {
t.wait();
} catch (InterruptedException ex) {
Logger.getLogger(NewJFrame.class.getName()).log(Level.SEVERE, null, ex);
}
继续:
t.notify();
线程类
public class DownloaderThread extends Thread{
@Override
public void run(){
Download();
}
public void Download() {
URL url = new URL(ftpUrl);
URLConnection conn = url.openConnection();
InputStream inputStream = conn.getInputStream();
FileOutputStream outputStream = new FileOutputStream(savePath);
byte[] buffer = new byte[BUFFER_SIZE];
int bytesRead = -1;
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
}
outputStream.close();
inputStream.close();
}
下载工作正常,下载文件没有任何错误,只是我无法使用 t.wait 停止线程。 我是否做错了什么或者我是否以错误的方式实现等待?
最佳答案
您需要更改 download()
方法来检查停止或暂停事件,然后停止或暂停线程。它必须是这样的,因为 JVM 不知道需要执行哪些步骤才能安全地暂停/停止线程。
您最终可能会使用wait
,但不是您使用它的方式。 wait
导致当前运行的线程等待,直到对您已调用 wait
的对象调用 notify
。
在下载方法中,您有一个循环(读取一个 block ,写入一个 block )。您应该在循环中添加两项检查。
while ((bytesRead = inputStream.read(buffer)) != -1) {
outputStream.write(buffer, 0, bytesRead);
if(paused) {
// How do you want to handle pausing? See below for options.
}
if(stopped) {
// delete the file and close the streams.
}
}
如何处理暂停取决于您。我可以看到两个选项: 将您拥有的内容保存为“.incomplete”,然后使用 Range 重新启动下载。 header 或继续循环并暂停(Thread.sleep、Object.wait 或其他)。 我会选择第一个选项(范围标题)。这是更多的工作,但也更稳健。
关于java - 暂停/恢复线程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33940571/