运行 javafx 中的后台任务

Running a background Task in javafx

大家好,我有一个问题,如何 运行 Javafx 中的后台任务

目前的情况是我在 javafx 中创建了一个复制函数,它工作得非常好,但是如果我们有更多的文件,那么它会进入无响应模式直到过程完成,日志也不会打印在我的 textarea,每个文件都被复制到受尊重的文件夹中,但问题是它挂起,直到过程完成,

还有一个问题如何 运行 这个程序永远意味着每当一个新文件进入源目录时它会自动转到目标目录。

这是我的代码

try
        {
            sourceFile = new File(sourcePath).listFiles();
            syslog.appendText("\nTotal Files in the Directory : " + sourceFile.length);
            for(int i = 0; i<sourceFile.length;i++)
            {
                if(sourceFile[i].isFile())
                {
                    String file = sourceFile[i].getName();
                    String extension = Files.getFileExtension(file);
                    if(!new File(destinationPath+"/"+extension.toUpperCase()).exists())
                    {
                        if(new File(destinationPath+"/"+extension.toUpperCase()).mkdir())
                        {
                            syslog.appendText("\nDirectory Created : " + destinationPath+"/"+extension.toUpperCase());
                            try
                            {
                                if(!new File(destinationPath+"/"+extension.toUpperCase()+"/"+file).exists())
                                {
                                    syslog.appendText("\nFile "+file+" is processing to copy to "+destinationPath+"/"+extension.toUpperCase());
                                    copyFile(sourceFile[i],new File(destinationPath+"/"+extension.toUpperCase()+"/"+file));
                                    syslog.appendText("\nFile "+file+" is successfully copied to "+destinationPath+"/"+extension.toUpperCase());
                                    if(sourceFile[i].delete())
                                        syslog.appendText("\nFile "+file+" is successfully deleted from "+sourcePath);
                                    else
                                        syslog.appendText("\nError in deleting File "+file+" from "+sourcePath);
                                }
                            }
                            catch(Exception e)
                            {
                                e.printStackTrace();
                                syslog.appendText("\nSome Error Occurred while copying the File : "+sourceFile[i]);
                            }
                        }
                    }
                    else
                    {
                        try
                        {
                            if(!new File(destinationPath+"/"+extension.toUpperCase()+"/"+file).exists())
                            {
                                syslog.appendText("\nFile "+file+" is processing to copy to "+destinationPath+"/"+extension.toUpperCase());
                                copyFile(sourceFile[i],new File(destinationPath+"/"+extension.toUpperCase()+"/"+file));
                                syslog.appendText("\nFile "+file+" is successfully copied to "+destinationPath+"/"+extension.toUpperCase());
                                if(sourceFile[i].delete())
                                    syslog.appendText("\nFile "+file+" is successfully deleted from "+sourcePath);
                                else
                                    syslog.appendText("\nError in deleting File "+file+" from "+sourcePath);
                            }
                        }
                        catch(Exception e)
                        {
                            e.printStackTrace();
                            syslog.appendText("\nSome Error Occurred while copying the File : "+sourceFile[i]);
                        }
                    }
                }
            }
            syslog.appendText("\nFinished..........");
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }

这是复制函数

    private static void copyFile(File source, File destination)
        throws IOException {
    FileChannel inputChannel = null;
    FileChannel outputChannel = null;
    try {
        inputChannel = new FileInputStream(source).getChannel();
        outputChannel = new FileOutputStream(destination).getChannel();
        outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
    } finally {
        inputChannel.close();
        outputChannel.close();
    }
}

您需要创建一个任务并将其添加到新线程。它看起来像这样:

        Task<T> backgroundTask = new Task<T>() {
        @Override
        protected T call() throws Exception {
            return null;
        }

        @Override
        public void run() {
            try {
                    copyFile(source,destination); //or any other operation you want to have in a thread.
                        } catch (IOException e) {
                           e.printStackTrace();
                        }
                }
        }
    };
    Thread backgroundThread = new Thread(backgroundTask);
    backgroundThread.setDaemon(true); //true if you want to have it running excuslivly when having your parent-threat running

您可以使用

调用并 运行 此线程一次
 backgroundThread.run();

您还可以使用

检查线程的状态
 backgroundThread.state();

如果您想检查,这可能会有所帮助,例如如果您的线程仍在处理中。

考虑与您的 javafx 线程的冲突。如果你想改变一个被 javafx 线程访问的对象,你需要执行一个

 Platform.runLater(new Runnable() {/*your impact on javafx*/}); 

我建议使用这样的任务:

    public class CopyFileTask<Void> extends Task<Void> {

    @Override
    protected void succeeded() {
        super.succeeded();
        // e.g. show "copy finished" dialog
    }

    @Override
    protected void running() {
        super.running();
        // e.g. change mouse courser
    }

    @Override
    protected void failed() {
        super.failed();
        // do stuff if call threw an excpetion
    }

    @Override
    protected Void call() {
        // do expensive the expensive stuff
        copyStuff(source, destination)
        return null ;
    }
}

便捷方法succeededrunningfailed在JavaFX GUI线程中执行,而call中的内容在另一个线程中执行。对于 运行 任务,我建议将其提交给 ExecuterService

 ExecutorService exService = Executors.newSingleThreadExecutor();
 exService.submit(new CopyFileTask());