繁体   English   中英

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

[英]Simplest way to use variable inside and outside a `syncExec` block (or, how to store a final reference to an object without initializing)

在此示例中,我成功地使用了AtomicReference (我发现这第一件事是syncExec并且可读),但是由于我还使用了syncExec并且直到该块执行完之后,才能访问sync块之外的部分。确实需要引用是原子的。 似乎太过分了。

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);

它输出The final local variable view cannot be assigned, since it is defined in an enclosing type 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阻止了线程,我相信这样做),它将起作用。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM