I am trying to multithread a for
loop, and this works so far. How can it be improved? Have I done anything incorrectly?
The work is broken up into blocks and the block
variable is the amount of objects to process per thread.
Test.class
public class Test extends MultiThreaded {
public static void main(String args[]) {
List<TestObject> values = new ArrayList<TestObject>();
for(int i = 1;i < 7;i++)
values.add(new TestObject(String.valueOf(i)));
int block = 2;
int cursor = 0;
List<TestObject> objectList = new ArrayList<TestObject>();
for(TestObject v : values) {
cursor++;
objectList.add(v);
if(cursor < block)
continue;
final List<TestObject> objectListCopy = new ArrayList<TestObject>();
objectListCopy.addAll(objectList);
Task task = new Task() {
@Override
public void run() {
for(TestObject o : objectListCopy)
o.print();
}
};
startTask(task);
objectList.clear();
cursor = 0;
}
while(MultiThreaded.processing()) { continue; }
System.out.println("move on");
}
public static class TestObject {
String line;
public TestObject(String string) {
this.line = string;
}
public void print() {
System.out.println(line);
}
}
}
MultiThreaded.class
public class MultiThreaded {
public static HashSet<Task> tasks = new HashSet<Task>();
public static class Task extends Thread {
public boolean running;
public void run(){
return;
}
}
public static void startTask(Task task) {
task.start();
tasks.add(task);
}
public static Task getTask(int id) {
for(Task task : tasks){
if(task.getId() == id)
return task;
}
return null;
}
public static boolean processing() {
boolean processing = false;
for(Task task: tasks){
if(task.isAlive())
processing = true;
}
return processing;
}
}
OUTPUT
1 2 5 6 3 4 move on