ThreadFactory usage in Java

前端 未结 10 1864
旧巷少年郎
旧巷少年郎 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:48

    Take a look at VerboseThreads (implements ThreadFactory) from jcabi-log. This implementation makes Threads that log exceptions when they are being thrown out of them. Very useful class when you need to see when and why your threads die.

    0 讨论(0)
  • 2020-12-02 05:51

    As mentioned by "InsertNickHere", you'll have to understand the Factory Pattern.

    A good example for a use of a ThreadFactory is the ThreadPoolExecutor: The Executor will create Threads if necessary and take care of the pooling. If you want to step in at the creation process and give special names to the created Threads, or assign them to a ThreadGroup, you can create a ThreadFactory for that purpose and give it to the Executor.

    It's a little bit IoC-style.

    0 讨论(0)
  • 2020-12-02 05:56

    The factory pattern is a creational design pattern used in software development to encapsulate the processes involved in the creation of objects.

    Let's assume we have some worker threads for different tasks and want them with special names (say for debugging purposes). So we could implement a ThreadFactory:

    public class WorkerThreadFactory implements ThreadFactory {
       private int counter = 0;
       private String prefix = "";
    
       public WorkerThreadFactory(String prefix) {
         this.prefix = prefix;
       }
    
       public Thread newThread(Runnable r) {
         return new Thread(r, prefix + "-" + counter++);
       }
    }
    

    If you had such a requirement, it would be pretty difficult to implement it without a factory or builder pattern.


    ThreadFactory is part of the Java API because it is used by other classes too. So the example above shows why we should use 'a factory to create Threads' in some occasions but, of course, there is absolutely no need to implement java.util.concurrent.ThreadFactory to accomplish this task.

    0 讨论(0)
  • 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());
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题