I have a thread that updates an array every 5 minutes.
It works fine however outside of the threads run(开发者_开发问答) method it seems I have no access to this array making it useless, any attempt I make to use it I just get null pointer exceptions.
I need the thread to update the array every 5 minutes but I also need to have access to the array from outside of this thread, what is the best way to do it?
Thanks
Declare the array as a private field of the class and instantiate it properly.
Example:
public class Controller implements Runnable {
private int[] array;
public Controller() {
array = new int[10];
for (int i = 1; i <= 10; i++) {
array[i - 1] = i;
}
}
public static void main(String[] args) {
Controller controller = new Controller();
Thread thread = new Thread(controller);
thread.start();
for (int i = 1; i < 5; i++) {
controller.printArray();
try {
Thread.sleep(1500);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void printArray() {
for (int i : array) {
System.out.println(i);
}
}
@Override
public void run() {
for (int i = 1; i < 10; i++) {
update(i);
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
private void update(int incr) {
for (int i = 0; i < array.length; i++) {
array[i] = array[i] + incr;
}
}
}
If it's just one array you are updating and once built it's never changed (including the elements of the array), your best option is to make the array reference volatile
. That is, the thread that updates the array does:
public volatile Object[] pubArray;
public void update() {
Object[] newArray = new Object[...];
//write to array
//finally, AFTER THE ARRAY IS BUILT, write to the reference:
this.pubArray = newArray;
}
If you are getting an NPE, you are not accessing the same reference.
You have to ensure you are using the same reference in both threads or you are not sharing the same array.
If you do need to update the same array in the thread while accessing it somewhere else, you need to use the 'synchronized' keyword on the methods that update or read the array. This will ensure that only one thread has access to the data. This will effectively serialize access to the array and will not scale. So only do it if you really really have to.
You may like to check out Java Concurrency in Practice.
精彩评论