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.
Thanks!
解决方案
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.