I have a driver class called Advantech which is stored inside an ArrayList. I instantiate and initialize my class. The Advantech class extends Thread and the Advantech class has a run() method. The thread is started within the class once it makes the connection to the device. (this.start();)
Is it possible to start the thread then store the instance of that class into an ArrayList?
When I instantiate the class and store it back into the array list (overwriting the previous position) with set(pos, class), I get NullPointerException when I call class.isAlive().
Are there any alternatives/better ways to do this?
I know this may sound strange, but I am using ArrayList because otherwise I have to create eight classes to start eight threads, for example:
Advantech adv1;
Advantech adv2;
Advantech adv3;
Advantech adv4;
All the parameters are the same for each instance.
Code:
private ArrayList<Advantech> advantech = null;
private Advantech adv = null;
....
adv = new Advantech(/* parameters */);
adv.initialize();
advantech.set(0, adv);
In Advantech.java:
public class Advantech extends Thread {
....
public void run() {
while(!done) { // do some work }
}
}
Unless I’ve missed something (or you just haven’t posted it), you don’t seem to have constructed your
ArrayList<Advantech>anywhere. You need this line before using it:Also, you might want to rename the list to something more descriptive (maybe
advantechThreadList.)