JAVAFX : 多任务

1. Task

package com.eternal.barcodeScanner.demo.javaFX;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.concurrent.TimeUnit;

public class Demo extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) {

        HBox hBox = new HBox(10);
        hBox.setAlignment(Pos.CENTER);

        ProgressBar pb = new ProgressBar(0);
        pb.setPrefWidth(200);

        Button start = new Button("开始");
        Button cancel = new Button("取消");

        Label l1 = new Label("state");
        Label l2 = new Label("value");
        Label l3 = new Label("title");
        Label l4 = new Label("message");

        AnchorPane an = new AnchorPane();
        an.setStyle("-fx-background-color: #ffffff");

        hBox.getChildren().addAll(start, cancel, pb, l1, l2, l3, l4);

        an.getChildren().add(hBox);

        AnchorPane.setTopAnchor(hBox, 100.0);
        AnchorPane.setLeftAnchor(hBox, 100.0);

        Scene scene = new Scene(an);
        stage.setScene(scene);
        stage.setHeight(800);
        stage.setWidth(800);
        stage.show();

        MyTask myTask = new MyTask();
        Thread thread = new Thread(myTask);

        start.setOnAction(event -> thread.start());  // 开始任务

        cancel.setOnAction(event -> myTask.cancel());  // 取消任务

        // 进度条监听 -> 更新进度条
        myTask.progressProperty().addListener((observable, oldValue, newValue) -> pb.setProgress(newValue.doubleValue()));

        myTask.titleProperty().addListener((observable, oldValue, newValue) -> l3.setText(newValue));

        myTask.valueProperty().addListener((observable, oldValue, newValue) -> {
            if (newValue.doubleValue() == 1)
                l2.setText("完成");
        });

        myTask.messageProperty().addListener((observable, oldValue, newValue) -> l4.setText(newValue));

        myTask.stateProperty().addListener((observable, oldValue, newValue) -> {
            l1.setText(newValue.toString());
            System.out.println("status: " + newValue);  //SCHEDULED/RUNNING/SUCCEEDED
        });

        // 异常监听
        myTask.exceptionProperty().addListener((observable, oldValue, newValue) -> {
            System.out.println("出现异常: " + newValue.getMessage());
        });

    }

}

class MyTask extends Task<Number> {

    @Override
    protected Number call() throws Exception {
        this.updateTitle("cope file");  // 任务名称
//        System.out.println(Thread.currentThread().getName() + (Platform.isFxApplicationThread() ? "UI线程" : "非UI线程"));

        String path = "F:/迅雷下载/Git-2.26.2-64-bit.exe";
        FileInputStream fis = new FileInputStream(new File(path));

        double total = fis.available();  // 获取文件字节长度
        double sum = 0.0;
        double progress = 0.0;

        String path_new = "C:/Users/Lenovo/Desktop/git_new.exe";
        FileOutputStream fos = new FileOutputStream(new File(path_new));

        byte[] bytes = new byte[1024];
        int length;

        while ((length = fis.read(bytes, 0, bytes.length)) != -1) {

            if (this.isCancelled())
                break;  // 取消任务
            fos.write(bytes, 0, length);
            sum += length;
            progress = sum /total;
//            System.out.println(progress);
            this.updateProgress(sum, total);
            if (progress < 0.5)
                this.updateMessage("请耐心等待");
            else if (progress < 0.8)
                this.updateMessage("马上就好");
            else if (progress < 1)
                this.updateMessage("即将完成");
            else
                this.updateMessage("搞定");
//            TimeUnit.MICROSECONDS.sleep(1);
        }

        fis.close();
        fos.close();

        return progress;
    }

    @Override
    protected void updateProgress(long workDone, long max) {
        super.updateProgress(workDone, max);
    }

    @Override
    protected void updateProgress(double workDone, double max) {
        super.updateProgress(workDone, max);
    }

    @Override
    protected void updateMessage(String message) {
        super.updateMessage(message);
    }

    @Override
    protected void updateTitle(String title) {
        super.updateTitle(title);
    }

    @Override
    protected void updateValue(Number value) {
        // UI线程, 可以更新界面
        super.updateValue(value);
//        System.out.println(Thread.currentThread().getName() + (Platform.isFxApplicationThread() ? "UI线程" : "非UI线程"));
//        System.out.println(value.intValue());
    }
}

2. Service

package com.eternal.barcodeScanner.demo.javaFX;

import javafx.application.Application;
import javafx.application.Platform;
import javafx.beans.value.ChangeListener;
import javafx.beans.value.ObservableValue;
import javafx.concurrent.Service;
import javafx.concurrent.Task;
import javafx.event.ActionEvent;
import javafx.event.EventHandler;
import javafx.geometry.Pos;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.layout.AnchorPane;
import javafx.scene.layout.HBox;
import javafx.stage.Stage;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

public class Demo extends Application {
    public static void main(String[] args) {
        launch(args);
    }

    @Override
    public void start(Stage stage) {

        HBox hBox = new HBox(10);
        hBox.setAlignment(Pos.CENTER);

        ProgressBar pb = new ProgressBar(0);
        pb.setPrefWidth(200);

        Button start = new Button("开始");
        Button cancel = new Button("取消");
        Button restart = new Button("重启");
        Button rest = new Button("重置");

        Label l1 = new Label("state");
        Label l2 = new Label("value");
        Label l3 = new Label("title");
        Label l4 = new Label("message");

        AnchorPane an = new AnchorPane();
        an.setStyle("-fx-background-color: #ffffff");

        hBox.getChildren().addAll(start, cancel, restart, rest, pb, l1, l2, l3, l4);

        an.getChildren().add(hBox);

        AnchorPane.setTopAnchor(hBox, 100.0);
        AnchorPane.setLeftAnchor(hBox, 100.0);

        Scene scene = new Scene(an);
        stage.setScene(scene);
        stage.setHeight(800);
        stage.setWidth(800);
        stage.show();

//        MyTask myTask = new MyTask();
//        Thread thread = new Thread(myTask);
//
//        start.setOnAction(event -> thread.start());  // 开始任务
//
//        cancel.setOnAction(event -> myTask.cancel());  // 取消任务
//
//        // 进度条监听 -> 更新进度条
//        myTask.progressProperty().addListener((observable, oldValue, newValue) -> pb.setProgress(newValue.doubleValue()));
//
//        myTask.titleProperty().addListener((observable, oldValue, newValue) -> l3.setText(newValue));
//
//        myTask.valueProperty().addListener((observable, oldValue, newValue) -> {
//            if (newValue.doubleValue() == 1)
//                l2.setText("完成");
//        });
//
//        myTask.messageProperty().addListener((observable, oldValue, newValue) -> l4.setText(newValue));
//
//        myTask.stateProperty().addListener((observable, oldValue, newValue) -> {
//            l1.setText(newValue.toString());
//            System.out.println("status: " + newValue);  //SCHEDULED/RUNNING/SUCCEEDED
//        });
//
//        // 异常监听
//        myTask.exceptionProperty().addListener((observable, oldValue, newValue) -> System.out.println("出现异常: " + newValue.getMessage()));


        MyService myService = new MyService();

        start.setOnAction(event -> myService.start());
        cancel.setOnAction(event -> myService.cancel());
        restart.setOnAction(event -> myService.restart());
        rest.setOnAction(event -> myService.reset());

        // 重置之后才能开启,否则报错


        myService.progressProperty().addListener((observable, oldValue, newValue) -> pb.setProgress(newValue.doubleValue()));
        myService.messageProperty().addListener((observable, oldValue, newValue) -> l4.setText(newValue));
    }

}


class MyService extends Service<Number> {

    @Override
    protected void ready() {
        super.ready();
        System.out.println("ready... : " + (Platform.isFxApplicationThread() ? "UI线程" : "非UI线程"));
    }

    @Override
    protected void scheduled() {
        super.scheduled();
        System.out.println("scheduled... : " + (Platform.isFxApplicationThread() ? "UI线程" : "非UI线程"));
    }

    @Override
    protected void running() {
        super.running();
        System.out.println("running... : " + (Platform.isFxApplicationThread() ? "UI线程" : "非UI线程"));
    }

    @Override
    protected void succeeded() {
        super.succeeded();
        System.out.println("succeeded... : " + (Platform.isFxApplicationThread() ? "UI线程" : "非UI线程"));
    }

    @Override
    protected void cancelled() {
        super.cancelled();
        System.out.println("cancelled... : " + (Platform.isFxApplicationThread() ? "UI线程" : "非UI线程"));
    }

    @Override
    protected void failed() {
        super.failed();
        System.out.println("failed... : " + (Platform.isFxApplicationThread() ? "UI线程" : "非UI线程"));
    }

    protected MyService() {
        super();
    }

    @Override
    public boolean cancel() {
        return super.cancel();
    }

    @Override
    public void restart() {
        super.restart();
    }

    @Override
    public void reset() {
        super.reset();
    }

    @Override
    public void start() {
        super.start();
    }

    @Override
    protected void executeTask(Task<Number> task) {
        super.executeTask(task);

        task.valueProperty().addListener((observable, oldValue, newValue) -> System.out.println(newValue));
    }

    @Override
    protected Task<Number> createTask() {
//        Task task = new Task() {
//            @Override
//            protected Number call() throws Exception {
//
//                // ... 和Task一致
//                return null;
//            }
//        };
//
//        return task;

        return new Task<Number>() {
            @Override
            protected Number call() throws Exception {

                // ... 和Task一致
                this.updateTitle("cope file");  // 任务名称
//        System.out.println(Thread.currentThread().getName() + (Platform.isFxApplicationThread() ? "UI线程" : "非UI线程"));

                String path = "F:/迅雷下载/Git-2.26.2-64-bit.exe";
                FileInputStream fis = new FileInputStream(new File(path));

                double total = fis.available();  // 获取文件字节长度
                double sum = 0.0;
                double progress = 0.0;

                String path_new = "C:/Users/Lenovo/Desktop/git_new.exe";
                FileOutputStream fos = new FileOutputStream(new File(path_new));

                byte[] bytes = new byte[1024];
                int length;

                while ((length = fis.read(bytes, 0, bytes.length)) != -1) {

                    if (this.isCancelled())
                        break;  // 取消任务
                    fos.write(bytes, 0, length);
                    sum += length;
                    progress = sum /total;
//            System.out.println(progress);
                    this.updateProgress(sum, total);
                    if (progress < 0.5)
                        this.updateMessage("请耐心等待");
                    else if (progress < 0.8)
                        this.updateMessage("马上就好");
                    else if (progress < 1)
                        this.updateMessage("即将完成");
                    else
                        this.updateMessage("搞定");
//            TimeUnit.MICROSECONDS.sleep(1);
                }

                fis.close();
                fos.close();

                return progress;
            }
        };
    }
}



//class MyTask extends Task {
//
//    @Override
//    protected Number call() throws Exception {
//        this.updateTitle("cope file");  // 任务名称
        System.out.println(Thread.currentThread().getName() + (Platform.isFxApplicationThread() ? "UI线程" : "非UI线程"));
//
//        String path = "F:/迅雷下载/Git-2.26.2-64-bit.exe";
//        FileInputStream fis = new FileInputStream(new File(path));
//
//        double total = fis.available();  // 获取文件字节长度
//        double sum = 0.0;
//        double progress = 0.0;
//
//        String path_new = "C:/Users/Lenovo/Desktop/git_new.exe";
//        FileOutputStream fos = new FileOutputStream(new File(path_new));
//
//        byte[] bytes = new byte[1024];
//        int length;
//
//        while ((length = fis.read(bytes, 0, bytes.length)) != -1) {
//
//            if (this.isCancelled())
//                break;  // 取消任务
//            fos.write(bytes, 0, length);
//            sum += length;
//            progress = sum /total;
            System.out.println(progress);
//            this.updateProgress(sum, total);
//            if (progress < 0.5)
//                this.updateMessage("请耐心等待");
//            else if (progress < 0.8)
//                this.updateMessage("马上就好");
//            else if (progress < 1)
//                this.updateMessage("即将完成");
//            else
//                this.updateMessage("搞定");
            TimeUnit.MICROSECONDS.sleep(1);
//        }
//
//        fis.close();
//        fos.close();
//
//        return progress;
//    }
//
//    @Override
//    protected void updateProgress(long workDone, long max) {
//        super.updateProgress(workDone, max);
//    }
//
//    @Override
//    protected void updateProgress(double workDone, double max) {
//        super.updateProgress(workDone, max);
//    }
//
//    @Override
//    protected void updateMessage(String message) {
//        super.updateMessage(message);
//    }
//
//    @Override
//    protected void updateTitle(String title) {
//        super.updateTitle(title);
//    }
//
//    @Override
//    protected void updateValue(Number value) {
//        // UI线程, 可以更新界面
//        super.updateValue(value);
        System.out.println(Thread.currentThread().getName() + (Platform.isFxApplicationThread() ? "UI线程" : "非UI线程"));
        System.out.println(value.intValue());
//    }
//}

3. ScheduledService

你可能感兴趣的:(#,Java)