Creating threadpool to execute tasks
The below code shows usage of util.concourrent.ExecutorService to create a thread pool.
The tasks are executed concurrently using the avilable number of fixed threads.
Below link tells us the difference of thread vs runnable interface
3) Runnable interface represent a Task which can be executed by either plain Thread or Executors or any other means. so logical separation of Task as Runnable than Thread is good design decision.
package com.anjana.threadpools;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import com.anjana.dao.TenantManager;
public class Main {
private static final int NTHREDS = 4;
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(NTHREDS);
TenantManager tm=new TenantManager();
List l3=new ArrayList();
List l=(List) tm.getVersionList(1);
List l2=(List) tm.getVersionList(2);
//l.size number of tasks will be created --all these tasks will be executed nthreads
for (int i = 0; i <l.size(); i++) {
executor.execute(new MyRunnable3(1,l.get(i).toString()));
}
//l2.size number of tasks will be created-all these tasks will be executed nthreads
for (int i = 0; i <l2.size(); i++) {
executor.execute(new MyRunnable3(2,l2.get(i).toString()));
}
//
executor.shutdown();
// Wait until all threads are finish
while (!executor.isTerminated()) {
}
System.out.println("Finished all threads");
}
}
package com.anjana.threadpools;
import java.util.ArrayList;
import java.util.List;
import com.anjana.dao.TenantManager;
public class MyRunnable3 implements Runnable {
private String FVERSION_NAME;
private int ITENANT_ID;
private static int taskCount = 0;
private final int id = taskCount++;
public MyRunnable3(int i, String string) {
// TODO Auto-generated constructor stub
this.ITENANT_ID=i;
this.FVERSION_NAME=string;
}
@Override
public void run() {
TenantManager tm=new TenantManager();
List l=new ArrayList();
if(!FVERSION_NAME.equals("DEFAULT")&& !FVERSION_NAME.equals("MASTER")){
tm.getVersionList(ITENANT_ID);
l=tm.editversion(ITENANT_ID, FVERSION_NAME);
System.out.println(ITENANT_ID+":"+FVERSION_NAME +":"+Thread.currentThread().getName()+"\n-----\n"+l+"-----\n");
Thread.yield();
}
// TODO Auto-generated method stub
}
}
Comments
Post a Comment