Let's assume I have a lot of objects:
public class Main {
public static DB d1 = new DB(1);
public static DB d2 = new DB(2);
public static DB d3 = new DB(3);
public static DB d4 = new DB(4);
and I want to modify them.
public static void main(String[] args) {
d1.modifyObject();
d2.modifyObject();
d3.modifyObject();
d4.modifyObject();
}
}
and I want them to be modified simultaneously, for it takes some time. Looks like I need multithreading.
This is my DB class:
import java.awt.EventQueue;
import java.util.Date;
import java.util.Random;
public class DB {
private int id = 0;
private long field = 0;
public void DB(int id) {
this.id = id;
}
// The contents of this method are not very important.
private void modifyField() {
// [some database interactions which take some seconds to execute]
// for simplicity, emulated with sleep:
long newValue = 0;
try {
newValue = (this.id + new Date().getTime()) % 42;
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
this.field = newValue;
}
public void modifyObject() {
Runnable r = new Runnable(){ @Override public void run() {
this.modifyField(); // THIS DOES NOT WORK OF COURSE, I can't access the objects content from a thread
}};
EventQueue.invokeLater(r);
}
}
I want the contents of Main.d1, Main.d2, Main.d3, Main.d4 and so on to be changed without delaying the main thread. I used to do it by accessing Main.d1 within DB itself. This obviously only works if I have just one object. Now, since I have to handle multiple objects, I can't access Main's objects statically any more.
My question is simple but I fear there is no easy answer to it: What options do I have to put this.modifyField(); into its own thread?
ExecutororExecutorServiceTHIS DOES NOT WORK OF COURSE, I can't access the objects content from a threadYou need to useDB.this