我对java很新,所以如果我说的话听起来很新鲜,那就要提前对不起.
我已经实现了一个基本的观察者模式.一些观察者应该只听一个更新,然后立即从观察者/听众列表中删除自己.但是,每当我尝试这样做时,我都会遇到着名的java.util.concurrentmodificationexception错误.
我显然遇到了这个错误,因为我在更改列表的同时还在迭代它,但我仍然不确定什么是正确的解决方案.我想知道我是否以正确的方式做到这一点.如果我是,那么它需要什么样的解决方案才能使它工作?如果我不是,我想得到更好的方法来实现我想要做的建议.
这是我的代码:
public interface Listener {
public void onValueChange(double newValue);
}
public class Observed {
private int value;
List<Listener> listeners = new ArrayList<>();
public void addListener(Listener toAdd) {
listeners.add(toAdd);
}
public void removeListener(Listener toRemove) {
listeners.remove(toRemove);
}
public void changeValue(double newValue) {
value = newValue;
for (Listener l : listeners) l.onValueChange(newValue);
}
}
public class SomeClassA implements Listener{
private Observed observed;
SomeClassA(Observed observed) {
this.observed = observed;
}
@Override
public void onValueChange(double newValue) {
System.out.println(newValue);
observed.removeListener(this); …
Run Code Online (Sandbox Code Playgroud) 这可能是一个非常简单的问题,但是在我认为之前我从未使用过线程,最好不要试图完全依靠自己找到最佳解决方案.
我有一个巨大的for
循环,几十亿次运行.在每个循环运行中,根据当前index
,程序以数字的形式计算最终结果.我只对存储顶部result
(或顶部x结果)及其相应的索引感兴趣.
我的问题很简单,在线程中运行此循环的正确方法是什么,因此它使用所有可用的CPU /核心.
int topResultIndex;
double topResult = 0;
for (i=1; i < 1000000000; ++i) {
double result = // some complicated calculation based on the current index
if (result > topResult) {
topResult = result;
topResultIndex = i;
}
}
Run Code Online (Sandbox Code Playgroud)
对于每个索引,计算完全独立,不共享资源.topResultIndex
并且topResult
显然会被每个线程访问.
*更新:Giulio和rolfl的解决方案都很好,也非常相似.只能接受其中一个作为我的答案.