我正在编写Eclipse插件,并且经常出现这样的情况:正在运行的Job需要暂停一段时间,在UI线程上异步运行某些东西,然后继续。 所以我的代码通常看起来像:
Display display = Display.getDefault();
display.syncExec(new Runnable() {
public void run() {
// Do some calculation
// How do I return a value from here?
}
});
// I want to be able to use the calculation result here!一种方法是让整个Job类都有一些字段。另一种方法是使用自定义类(而不是匿名类,并使用其生成的数据字段等。 什么是最好,最优雅的方法?
正确的解决方案是使用AtomicReference:
final AtomicReference<Object> result = new AtomicReference<Object>();
Display display = Display.getDefault();
display.syncExec(new Runnable()
{
public void run()
{
result.set("foo");
}
}
System.out.println(result.get());所有线程都保证可以看到对AtomicReference值的更改,就像它被声明为volatile一样。
- 本文固定链接: https://www.coordsoft.com/post/18.html
- 转载请注明: admin 于 生活随想 - zwgu 's world 发表
《本文》有 0 条评论