在“syncExec”块内外使用变量的最简单方法(或者,如何在不初始化的情况下存储对对象的最终引用)



我在这个例子中成功地使用了AtomicReference(我发现的第一件事是有效的并且可读的),但由于我也在syncExec并且同步块之外的部分在块完成执行之前不会到达,我真的不需要引用是原子的。这似乎矫枉过正。

final AtomicReference<Custom> result = new AtomicReference<>();
PlatformUI.getWorkbench().getDisplay().syncExec( () -> {
    Custom custom = getSomeCustom();
    custom.doSomething();
    result.set(custom);
});
Custom c = result.get();
c.doSomethingElse();

我试图使用常规引用,但我无法让它工作:

final Custom c;
PlatformUI.getWorkbench().getDisplay().syncExec( () -> {
    c= getSomeCustom();
    c.doSomething();
});
c.doSomethingElse(true);

它在getSomeCustom()调用时输出The final local variable view cannot be assigned, since it is defined in an enclosing type

我也尝试过使用 Reference 及其实现,但它们似乎不是我想要的(这是执行此操作的最易读和最基本的方法)。有没有人知道如何在不使用AtomicReference的情况下实现这一目标?

我建议定义一个接受Supplier的自定义静态方法:

public class UIUtils {
    static <T> T syncExec(Supplier<T> supplier) {
        Object[] obj = new Object[1];
        PlatformUI.getWorkbench().getDisplay().syncExec( () -> {
            obj[0] = supplier.get();
        });
        return (T)obj[0];
    }
}

使用单元素数组时有点脏,但你只需要编写一次此方法。之后,您可以使用:

Custom c = UIUtils.syncExec(() -> {
    Custom custom = getSomeCustom();
    custom.doSomething();
    return custom;
});
c.doSomethingElse();

管理这一点的最简单方法是有一个最终变量,你可以在其中添加一些东西。例如:

final Custom[] customHolder = new Custom[1];
PlatformUI.getWorkbench().getDisplay().syncExec(() -> {
    customHolder[0] = getSomeCustom();
    customHolder[0].doSomething();
});
customHolder[0].doSomethingElse(true);

只要保证在下一行之前调用 lambda 函数(即如果 syncExec 阻塞线程,我相信它确实如此),这将起作用。

相关内容

最新更新