JavaFX线程与Java线程的同步 [英] JavaFX thread synchronization with Java thread

查看:130
本文介绍了JavaFX线程与Java线程的同步的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法同步JavaFX Platform线程和标准Java线程?当前,当触发时,JavaFX线程会在标准Java线程完成将所有图像添加到可观察列表之前触发,因此imageList会更新为空白集合.

Is there a way to synchronize a JavaFX Platform thread and a standard Java thread? Currently, when triggered, the JavaFX thread fires before the standard Java thread has finished adding all of the images to the observable list, and so the imageList is updated with a blank collection.

private final TilePane imageList;
final File[] files = new File(dir).listFiles();
final List<ImageView> views = FXCollections.observableArrayList();

new Thread() {
        @Override
        public void run() {
            for (final File file : files) {
                if (Utils.fileIsImage(file) && !file.isDirectory()) {
                    ImageView view = new ImageView(new Image("file:" + file, 72, 72, false, true));
                    views.add(view);
                }
            }
        }
    }.start();
    Platform.runLater(new Runnable() {
        @Override
        public void run() {
            imageList.getChildren().addAll(views);
        }
    });

我对JavaFX和并发性还比较陌生,并且对线程锁没有任何经验,因此任何帮助都将非常有用.谢谢!

I'm relatively new to JavaFX and concurrency, and don't have any experience with thread locks, so any help would be great. Thanks!

推荐答案

new Thread() {
    @Override
    public void run() {
        for (final File file : files) {
            if (Utils.fileIsImage(file) && !file.isDirectory()) {
                ImageView view = new ImageView(new Image("file:" + file, 72, 72, false, true));
                views.add(view);
            }
        }

        Platform.runLater(new Runnable() {
            @Override
            public void run() {
                imageList.getChildren().addAll(views);
            }
        });
    }
}.start();

考虑只要加载视图,就一一添加视图:

Consider adding views one by one as long as they are loaded:

if (Utils.fileIsImage(file) && !file.isDirectory()) {
    ImageView view = new ImageView(new Image("file:" + file, 72, 72, false, true));
    views.add(view);

    Platform.runLater(new Runnable() {
        @Override
        public void run() {
            imageList.getChildren().add(view);
        }
    });
}

这篇关于JavaFX线程与Java线程的同步的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆