ThreadFactory在Java中的用法 [英] ThreadFactory usage in Java

查看:291
本文介绍了ThreadFactory在Java中的用法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有人可以简单解释一下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.

谢谢!

推荐答案


工厂模式是一种用于软件开发的创意设计模式,对象的创建。

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

让我们假设我们有一些工作线程用于不同的任务,并希望它们有特殊的名字。所以我们可以实现一个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中的用法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆