Multi threaded worker sample
A Simple program to achieve multi task using multi thread in java
package myProject;
import java.util.ArrayList;
import java.util.List;
public class SampleThreadProcessor {
static List lst = new ArrayList<>();
public static void main(String[] args) throws InterruptedException {
ThreadGroup tg = new ThreadGroup("Group A");
for (int i = 0; i < 115; i++) {
lst.add(i);
}
System.out.println(lst);
int startCount = 0;
int endCount = 0;
int recPerBatch = 15;
int maxThreadCount = Runtime.getRuntime().availableProcessors() * 2;
System.out.println("###### maxThreadCount "+maxThreadCount);
System.out.println(lst.size() / recPerBatch);
System.out.println(tg.activeCount());
while (true) {
if (tg.activeCount() <= maxThreadCount) {
System.out.println("Thread count = " + tg.activeCount());
endCount = startCount + recPerBatch;
if (endCount > lst.size()) {
endCount = lst.size();
}
if (startCount < lst.size()) {
System.out.println("Starting theard from " + startCount + " to " + endCount);
Thread t = new Thread1(tg, lst.subList(startCount, endCount), tg.activeCount()+1);
Thread.sleep(1000);
t.start();
startCount = endCount;
} else {
break;
}
System.out.println("#########" + startCount);
} else if (tg.activeCount() == 0) {
break;
}
}
System.out.println(tg.activeCount());
System.out.println("done");
}
}
class Thread1 extends Thread {
List lst = null;
Thread1(ThreadGroup tg, List sst, int thCnt) {
super(tg, "");
lst = sst;
this.setName("Thread "+thCnt);
}
public void run() {
System.out.println("Thread started" + lst);
try {
Thread.sleep(15000);
System.out.println(this.getName());
} catch (InterruptedException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}