I am retrieving some values from DB in form of ArrayList of 240 size and creating a sub list from this list of 8 values each. I want to do some processing on this sub list which will be passed as the parameter to the thread.
I am creating the thread object in the for loop where this sub list is created and passed to the thread. But I am facing problems that I have to wait till one thread finishes its work because the parameter is global in the thread and gives concurrency error.
How can I not make it a global variable and do processing on my sub list without waiting for 1 thread to finish, I want to send parallel requests and process this sub list.
Please see some code I m writing:
Class a {
for(int j=0; j<240; j++) {
subOrders.add(orders.get(j));
if(subOrders.size()==8)
{
TestThread test = new TestThread(subOrders);
try {
test.t.join();
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
subOrders.clear();
}
}
}
Thread Class :
public class TestThread implements Runnable {
ArrayList<Integer> b ;
public Thread t;
public TestThread(ArrayList<Integer> a) {
b=a;
t= new Thread(this);
t.start();
}
@Override
public void run() {
ArrayList<Integer> c = b;
System.out.println(c);
try {
Thread.sleep(5000);
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
This is the normal way you would pass data to a thread. Note that this method requires that the variable be declared final. The first way of obtaining the sub list is fine if you do not need to alter the sublist. The second can be modified without having to worry about synchronisation issues (any modifications will not be reflected in the global orders list).