【问题标题】:how to pause and resume a download in javafx如何在 javafx 中暂停和恢复下载
【发布时间】:2015-06-09 18:33:08
【问题描述】:

我正在 javafx 中构建一个下载管理器

我在下载按钮上添加了初始化新任务的功能。多个下载也正在正确执行。

但是我需要添加暂停和恢复功能。请告诉如何使用执行器来实现它。通过 Executors 的执行功能,任务正在启动,但我如何暂停然后恢复它??

下面我展示了我的代码的相关部分。请告诉您是否需要更多详细信息。谢谢。

主类

public class Controller implements Initializable {

    public Button addDownloadButton;
    public Button pauseResumeButton;
    public TextField urlTextBox;
    public TableView<DownloadEntry> downloadsTable;
    ExecutorService executor;

    @Override
    public void initialize(URL location, ResourceBundle resources) {

        // here tableview and table columns are initialised and cellValueFactory is set

        executor = Executors.newFixedThreadPool(4);
    }

    public void addDownloadButtonClicked() {
        DownloadEntry task = new DownloadEntry(new URL(urlTextBox.getText()));
        downloadsTable.getItems().add(task);
        executor.execute(task);
    }


    public void pauseResumeButtonClicked() {
        //CODE FOR PAUSE AND RESUME
    }
}

下载条目.java

public class DownloadEntry extends Task<Void> {

    public URL url;
    public int downloaded;
    final int MAX_BUFFER_SIZE=50*1024;
    private String status;

    //Constructor
    public DownloadEntry(URL ur) throws Exception{
        url = ur;
        //other variables are initialised here
        this.updateMessage("Downloading");
    }

    @Override
    protected Void call() {
        file = new RandomAccessFile(filename, "rw");
        file.seek(downloaded);
        stream = con.getInputStream();

        while (status.equals("Downloading")) {
            byte buffer=new byte[MAX_BUFFER_SIZE];

            int c=stream.read(buffer);
            if (c==-1){
                break;
            }
            file.write(buffer,0,c);
            downloaded += c;
            status = "Downloading";
        }
        if (status.equals("Downloading")) {
            status = "Complete";
            updateMessage("Complete");
        } 
        return null;
    }

}

【问题讨论】:

    标签: url download javafx executorservice resume


    【解决方案1】:

    您可能对Concurrency in JavaFX感兴趣。

    我想你也应该看看模式Observer

    顺便说一句,我认为您不应该使用常量字符串作为状态(“正在下载”等),创建枚举将是更好的方法。

    在您的循环中,围绕读/写部分,应该有一个同步机制,由您的暂停/恢复按钮控制(参见两个链接)。

    【讨论】:

    • 我已经更改了与字符串的比较。但是我查看了您的链接,它们似乎对我没有帮助。第一个链接中没有提到如何执行任务。
    • 作为概念证明,您可以在您的 DownloadEntry 中添加一个 volatile 布尔属性“isPaused”,并在您在 while 循环中创建缓冲区后检查其状态。如果属性“isPaused”为真,则跳过读/写步骤。另外,您需要一个设置器(用于 isPause),您将在暂停和恢复按钮中使用它。但我认为您希望能够同时暂停/恢复所有条目。这就是我考虑观察者模式的原因(您的 DownloadEntry 应该期待任何暂停/恢复事件)。
    猜你喜欢
    • 1970-01-01
    • 2011-01-03
    • 2012-08-27
    • 1970-01-01
    • 1970-01-01
    • 2012-11-26
    • 1970-01-01
    • 2017-09-07
    • 2011-02-27
    相关资源
    最近更新 更多