ThreadFactory in Java
April 18, 2019
java.util.concurrent.ThreadFactory
creates a new thread and has been introduced in JDK 5. ThreadFactory
is an interface and is implemented by a user class to override it. ThreadFactory
has a method as newThread()
and it is overridden to fulfill any specific requirement. Java provides defaultThreadFactory method of Executors
as one of the ThreadFactory
implementation. Here we will create our own ThreadFactory
as an example with simple usage.
1. Find the thread factory that will create all thread as daemon.
DaemonThreadFactory.java
package com.concretepage; import java.util.concurrent.ThreadFactory; public class DaemonThreadFactory implements ThreadFactory{ @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setDaemon(true); return t; } }
MaxPriorityThreadFactory.java
package com.concretepage; import java.util.concurrent.ThreadFactory; public class MaxPriorityThreadFactory implements ThreadFactory{ @Override public Thread newThread(Runnable r) { Thread t = new Thread(r); t.setPriority(Thread.MAX_PRIORITY ); return t; } }
ThreadFactoryDemo.java
package com.concretepage; public class ThreadFactoryDemo { public static void main(String[] args) { DaemonThreadFactory daemontf = new DaemonThreadFactory(); MaxPriorityThreadFactory mptf = new MaxPriorityThreadFactory(); Runnable r = new SimpleTask("High Priority"); mptf.newThread(r).start(); r = new SimpleTask("Low Priority"); daemontf.newThread(r).start(); } } class SimpleTask implements Runnable{ String s = null; public SimpleTask(String s){ this.s = s; } @Override public void run() { System.out.println(s+" Simple task done."); } }
High Priority Simple task done. Low Priority Simple task done.