问题描述
有人可以简单解释一下HOW和WHEN如何使用ThreadFactory?有和没有使用ThreadFactory的例子可能真正有助于了解差异。
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.
谢谢!
推荐答案
让我们假设我们有一些工作线程用于不同的任务,并希望它们有特殊的名字。所以我们可以实现一个ThreadFactory:
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
是Java API的一部分,因为它也被其他类使用。所以上面的例子显示了为什么我们应该在某些场合使用'工厂来创建Threads',当然,绝对没有必要实现 java.util.concurrent.ThreadFactory
完成此任务。
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.
这篇关于ThreadFactory在Java中的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!