ThreadFactory usage in Java

前端 未结 10 1892
旧巷少年郎
旧巷少年郎 2020-12-02 05:08

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.

10条回答
  •  伪装坚强ぢ
    2020-12-02 05:57

    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());
            }
        }
    }
    

提交回复
热议问题