"" - " , ", " ".
:
public static class Main {
public static ClassA a = new ClassA();
public static ClassB b = new ClassB();
private static List<Runnable> requestQueue = new ArrayList<Runnable>();
public static void main(String args[]) {
while (true) {
a.tick();
b.tick();
for (Runnable r : requestQueue) {
r.run();
}
requestQueue.clear();
}
}
public static void addModificationRequest(Runnable runnable) {
requestQueue.add(runnable);
}
}
addModificationRequest :
Main.addModificationRequest(new Runnable() {
public void run() {
Main.b.name = "NewNameB";
}
});
, ConcurrentModificationException, addModificationRequest , foreach. synchronized addModificationRequest + , .
Edit:
, , :
interface FieldUpdater extends Runnable
{
Field getField();
}
static class Main
{
public static ClassA a = new ClassA();
public static ClassB b = new ClassB();
private static List<FieldUpdater> requestQueue = new ArrayList<FieldUpdater>();
private static Set<Field> seenBefore = new HashSet<Field>();
public void main(String args[])
{
while (true)
{
a.tick();
b.tick();
for (FieldUpdater r : requestQueue)
{
if (seenBefore.contains(r.getField()))
{
continue;
}
seenBefore.add(r.getField());
r.run();
}
requestQueue.clear();
}
}
public synchronized static void addModificationRequest(FieldUpdater fieldUpdater)
{
requestQueue.add(fieldUpdater);
}
}
:
Main.addModificationRequest(new FieldUpdater()
{
public void run()
{
Main.b.name = "NewNameB";
}
public Field getField()
{
return Main.class.getField("name");
}
});
Note that for clarity, I deliberately skipped work with Exceptions that can be fetched from getField (). Also, this is not a good code design, but it fixes your code as indicated.
source
share