Can someone briefly explain on HOW and WHEN to use a ThreadFactory? An example with and without using ThreadFactory might be really helpful to understand the differences.
ThreadFactory is an interface with a single method
public abstract java.lang.Thread newThread(java.lang.Runnable arg0);
Its usage depends on your requirement. Suppose you want a particular functionality to always create Daemon threads. You can easily achieve this with ThreadFactory.
The below code is just for telling the fundamental. It is not doing any specific functionality.
package TestClasses;
import java.util.concurrent.ThreadFactory;
public class ThreadFactoryEx implements ThreadFactory{
@Override
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setDaemon(true);
return t;
}
}
package TestClasses;
import java.util.concurrent.ThreadPoolExecutor;
public class RunnableEx implements Runnable{
@Override
public void run() {
// TODO Auto-generated method stub
for (int i = 0; i < 5; i++) {
System.out.println("in a loop" + i + "times");
}
}
}
package TestClasses;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Thread1 {
public static void main(String[] args) {
ExecutorService exe = Executors.newCachedThreadPool(new ThreadFactoryEx());
for (int i = 0; i < 4; i++) {
exe.execute(new RunnableEx());
}
}
}