[英]How to access Runnable during Thread creation inside ThreadFactory?
I have a ThreadPoolExecutor
I've created with a custom ThreadFactory
. 我有一个使用自定义
ThreadFactory
创建的ThreadPoolExecutor
。 When I call the execute()
method passing my Runnable
, a new Thread
is created using my custom ThreadFactory
. 当我通过
Runnable
调用execute()
方法时,将使用自定义ThreadFactory
创建一个新Thread
。 The problem is I can't find a way to access information inside the Runnable
. 问题是我找不到在
Runnable
内部访问信息的方法。
For example, I have a class Job
that implements Runnable
. 例如,我有一个实现
Runnable
Job
类。 Inside Job
, I have a property A
that I would like to access in the newThread()
method of my custom ThreadFactory
. 在
Job
内部,我想在自定义ThreadFactory
的newThread()
方法中访问属性A
The problem is that I can't cast the Runnable
passed as parameter to Job
since it's not a Job
instance, it is an instance of the ThreadPoolExecutor.Worker
class, and this class is private
. 问题是我无法将作为参数传递的
Runnable
为Job
因为它不是Job
实例,它是ThreadPoolExecutor.Worker
类的实例,并且该类是private
。
You are either misusing or misunderstanding what thread pool does. 您要么滥用,要么误解了线程池的作用。 The process of creating threads and submitting/running tasks is completely decoupled.
创建线程和提交/运行任务的过程完全分离。 Thread pool decides when create a new thread and it might not be related to any new task submitted at all.
线程池决定何时创建新线程,它可能根本与提交的任何新任务都不相关。
And finally remember that one thread is most likely reused across several Runnable
s. 最后要记住,一个线程很可能在多个
Runnable
重用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.