从另一个线程javafx调用线程

时间:2017-05-20 08:53:19

标签: multithreading javafx java-threads

我一直在尝试在两个线程上运行两个任务,并在进度条和进度指示器上显示它们的进度。

第一项任务是copyTask,第二项是复制文件。 copyTask将文件对象发送到copyFile以进行文件复制。  但问题是只复制一个文件,文件计数似乎是正确的。

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.List;
import java.util.ResourceBundle;
import java.util.concurrent.CountDownLatch;
import javafx.concurrent.Task;
import javafx.concurrent.WorkerStateEvent;
import javafx.event.EventHandler;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.TextArea;

/**
 * FXML Controller class
 *
 * @author ANIL
 */
public class ProgressIndicateController implements Initializable {

    @FXML
    private ProgressIndicator uploadIndicator;
    @FXML
    private ProgressBar uploadBar;
    @FXML
    private TextArea errTxt;
    @FXML
    private Label uploadTxt;

    File f;
    Thread parent,child;
    CountDownLatch latch = new CountDownLatch(1);

    @FXML
    private Label sizeTXT;

//    private CopyTask copyTask;
    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO

        // Unbind progress property
        uploadBar.progressProperty().unbind();

        // Bind progress property
        uploadBar.progressProperty().bind(copyFile.progressProperty());

        // Hủy bỏ kết nối thuộc tính progress
        uploadIndicator.progressProperty().unbind();

        // Bind progress property.
        uploadIndicator.progressProperty().bind(copyTask.progressProperty());

        // Unbind text property for Label.
        uploadTxt.textProperty().unbind();

        // Bind the text property of Label
        // with message property of Task
        uploadTxt.textProperty().bind(copyTask.messageProperty());

        // Unbind text property for Label.
        sizeTXT.textProperty().unbind();

        // Bind the text property of Label
        // with message property of Task
        sizeTXT.textProperty().bind(copyFile.messageProperty());

        // When completed tasks
        copyTask.addEventHandler(WorkerStateEvent.WORKER_STATE_SUCCEEDED, //
                new EventHandler<WorkerStateEvent>() {

            @Override
            public void handle(WorkerStateEvent t) {
                List<File> copied = copyTask.getValue();
                uploadTxt.textProperty().unbind();
                uploadTxt.setText("Copied: " + copied.size());
            }
        });
        copyFile.addEventHandler(WorkerStateEvent.WORKER_STATE_SUCCEEDED, //
                new EventHandler<WorkerStateEvent>() {

            @Override
            public void handle(WorkerStateEvent t) {
                File copied = copyFile.getValue();
                sizeTXT.textProperty().unbind();
                sizeTXT.setText("Copied: " + copied.getAbsolutePath());
            }

        });

        // Start the Task.
       parent= new Thread(copyTask);
       parent.start();

    }
    Task<List<File>> copyTask = new Task<List<File>>() {
        @Override
        protected List<File> call() throws Exception {
            File dir = new File("F:");
            File[] files = dir.listFiles();
            int count = files.length;

            List<File> copied = new ArrayList<File>();
            int i = 0;
            for (File file : files) {
                if (file.isFile()) {
                    this.copy(file);
                    copied.add(file);
                }
                i++;
                this.updateProgress(i, count);
            }
            return copied;
        }

        private void copy(File file) throws Exception {

            this.updateMessage("Copying: " + file.getAbsolutePath());
            f = file;
            child=new Thread(copyFile);            
            child.start();
            this.wait();

        }
    };
    Task<File> copyFile = new Task<File>() {
        @Override
        protected File call() throws Exception {
            InputStream is = null;
            OutputStream os = null;
            File dest=null;

                String name=f.getName();
                dest=new File("D:\\OUTPUT\\"+name);
                is = new FileInputStream(f);
                os = new FileOutputStream(dest);
                byte[] buffer = new byte[1024];
                int length;
                double i=0.0;
                double l=f.length();
                while ((length = is.read(buffer)) > 0) {
                    i+=length;
                    this.updateMessage("Copying: " + i +" bytes of " + l);
                    os.write(buffer, 0, length);                     
                    this.updateProgress(i, l);
                    Thread.sleep(500);
                }
                is.close();
                os.close();
                this.notifyAll();
                return dest;
            }


    };
}

新守则:

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.URL;
import java.util.ResourceBundle;
import java.util.concurrent.CyclicBarrier;
import javafx.beans.property.SimpleDoubleProperty;
import javafx.beans.property.SimpleStringProperty;
import javafx.fxml.FXML;
import javafx.fxml.Initializable;
import javafx.scene.control.Label;
import javafx.scene.control.ProgressBar;
import javafx.scene.control.ProgressIndicator;
import javafx.scene.control.TextArea;

/**
 * FXML Controller class
 *
 * @author ANIL
 */
public class ProgressIndicateController implements Initializable {

    @FXML
    private ProgressIndicator uploadIndicator;
    @FXML
    private ProgressBar uploadBar;
    @FXML
    private TextArea errTxt;
    @FXML
    private Label uploadTxt;

    @FXML
    private Label sizeTXT;

    CyclicBarrier cb = new CyclicBarrier(2);

    final SimpleDoubleProperty prog1 = new SimpleDoubleProperty(0);
    final SimpleDoubleProperty prog2 = new SimpleDoubleProperty(0);
    final SimpleStringProperty text1 = new SimpleStringProperty("");
    final SimpleStringProperty text2 = new SimpleStringProperty("");
    final SimpleStringProperty err = new SimpleStringProperty("");

    /**
     * Initializes the controller class.
     */
    @Override
    public void initialize(URL url, ResourceBundle rb) {
        // TODO


        // Unbind progress property
        uploadBar.progressProperty().unbind();

        // Bind progress property
        uploadBar.progressProperty().bind(prog2);

        // Hủy bỏ kết nối thuộc tính progress
        uploadIndicator.progressProperty().unbind();

        // Bind progress property.
        uploadIndicator.progressProperty().bind(prog1);

        // Unbind text property for Label.
        uploadTxt.textProperty().unbind();

        // Bind the text property of Label
        // with message property of Task
        uploadTxt.textProperty().bind(text1);

        // Unbind text property for Label.
        sizeTXT.textProperty().unbind();

        // Bind the text property of Label
        // with message property of Task
        sizeTXT.textProperty().bind(text2);

        //When completed tasks
        errTxt.textProperty().unbind();

        errTxt.textProperty().bind(err);

        // Start the Task.
        new Thread() {
            @Override
            public void run() {
                File dir = new File("F:");
                File[] files = dir.listFiles();
                int count = files.length;                
                int i = 0;
                for (File file : files) {
                    if (file.isFile()) {
                        try {

                            text1.setValue("Copying: " + file.getAbsolutePath());

                            InputStream is = null;
                            OutputStream os = null;
                            File dest = null;

                            String name = file.getName();
                            dest = new File("D:\\OUTPUT\\" + name);
                            is = new FileInputStream(file);
                            os = new FileOutputStream(dest);
                            byte[] buffer = new byte[1024];
                            int length;
                            double j = 0.0;
                            double l = file.length();
                            while ((length = is.read(buffer)) > 0) {
                                j += length;
                                text2.setValue("Copying: " + j + " bytes of " + l);
                                os.write(buffer, 0, length);
                                prog2.setValue(j / l);
                                Thread.sleep(100);
                            }
                            is.close();
                            os.close();

                        } catch (Exception ex) {
                            err.setValue(ex.toString());
                        }

                        i++;
                        prog1.setValue(i / count);
                    }

                }
            }
        }.start();
    }

}

0 个答案:

没有答案