Just create an anonymous ThreadFactory for getting the Executor Service.
The ThreadFactory can supply the name for the thread as follows: "Thread A" or "Thread B" (see the example).
Then call the callable task using the different executor services:
Example Class:
public class ThreadTester {
public static void main(String[] args) {
ThreadTester threadTester = new ThreadTester();
threadTester.test();
}
private void test() {
ExecutorService executorservice = Executors.newCachedThreadPool(new ThreadFactory() {
@Override
public Thread newThread(Runnable arg0) {
return new Thread(arg0,"Thread A");
}
});
CallableTask taskA = new CallableTask();
executorservice.submit(taskA);
executorservice = Executors.newCachedThreadPool(new ThreadFactory() {
@Override
public Thread newThread(Runnable arg0) {
return new Thread(arg0,"Thread B");
}
});
CallableTask taskB = new CallableTask();
executorservice.submit(taskB);
}
}
Callable Task :
public class CallableTask implements Callable {
@Override
public Integer call() throws Exception {
int sum = 0;
for(int count=1;count<=30;count++){
try {
Thread.sleep(300);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(Thread.currentThread().getName() + " Count :"+count);
sum = sum + count;
}
System.out.println(Thread.currentThread().getName() + " Sum :"+sum);
return sum;
}
}