ThreadFactory Interface in Java with Examples
The ThreadFactory
interface in Java is used to create new threads. It provides a way to encapsulate the creation of threads in a separate class, which can be useful for managing thread creation in a centralized way. The ThreadFactory
interface has only one method, newThread()
, which is used to create a new thread.
Here is the syntax for the ThreadFactory
interface:
public interface ThreadFactory {
Thread newThread(Runnable r);
}
The newThread()
method takes a Runnable
object as a parameter and returns a new Thread
object.
Here is an example of how to use the ThreadFactory
interface:
import java.util.concurrent.*;
public class MyThreadFactory implements ThreadFactory {
private final String namePrefix;
private final int priority;
public MyThreadFactory(String namePrefix, int priority) {
this.namePrefix = namePrefix;
this.priority = priority;
}
public Thread newThread(Runnable r) {
Thread t = new Thread(r);
t.setName(namePrefix + "-" + t.getId());
t.setPriority(priority);
return t;
}
}
In this example, we create a custom ThreadFactory
implementation called MyThreadFactory
. This implementation takes two parameters: a namePrefix
and a priority
. The namePrefix
is used to give a name to the threads created by this factory, and the priority
is used to set the priority of the threads.
The newThread()
method creates a new Thread
object, sets its name and priority, and returns it.
Here is an example of how to use the MyThreadFactory
class:
public class Main {
public static void main(String[] args) {
ExecutorService executor = Executors.newFixedThreadPool(2, new MyThreadFactory("MyThread", Thread.MAX_PRIORITY));
executor.execute(new MyRunnable());
executor.execute(new MyRunnable());
executor.shutdown();
}
}
class MyRunnable implements Runnable {
public void run() {
System.out.println("Thread " + Thread.currentThread().getName() + " is running");
}
}
In this example, we create an ExecutorService
with a fixed thread pool of 2 threads, using the MyThreadFactory
class to create the threads. We then submit two Runnable
tasks to the executor, which will be executed by the threads created by the MyThreadFactory
. Finally, we shut down the executor.
When we run this program, we should see output like this:
Thread MyThread-1 is running
Thread MyThread-2 is running
This shows that the threads created by the MyThreadFactory
have the names and priorities that we specified.