我正在尝试使用自定义
ThreadFactory
实现,它允许我使用自定义对象而不是通用 Runnable
对象。
下面是我所能提供的最小示例。除了为我的问题创建功能支架之外,
Foo()
类定义和Main()
在很大程度上无关紧要。我正在使用 ExecutorService
的 execute()
方法来调用我的 ExampleFactory
。这个问题很大程度上涉及通过 ThreadFactory
调用时如何正确利用重载的 ExecutorService
。代码后面的上下文。
import java.lang.Runnable;
import java.util.concurrent.ThreadFactory
class ExampleFactory implements ThreadFactory{
public Thread newThread(Foo f){
String threadName = "ID: " + f.getID();
return new Thread(f, threadName);
}
@Override
public Thread newThread(Runnable r){
if (! (r instanceof Foo)) {
throw new IllegalArugmentException("Not Foo");
}
return new Thread(r, "Boo"); //won't get here, thrown exception
}
}
...
import java.lang.Runnable;
public class Foo implements Runnable{
public int ID = 0;
public Foo(int i){
this.ID = i;
}
public int getID(){
return this.ID;
}
@Override
public void run() {
System.out.println("Running (Runnable): " + this.ID);
}
}
...
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
public class Main {
public static void main(String[] args) {
ExecutorService e = Executors.newFixedThreadPool(10, new ExampleFactory());
for (int i = 0; i < 100; i++){
Foo f = new Foo( i );
System.out.println("Executing i: "+ i);
e.execute(f);
}
}
}
使用
ExecutorService
时,我没有看到 newThread(Foo f)
被呼叫,而是看到 newThread(Runnable r)
。
有更好的方法吗?
我希望能够从线程工厂中的
Foo
调用 getter 方法,用于预.start()
之前的标记和其他目的。
发生这种情况似乎是因为
ExecutorService
的 execute()
方法需要一个 Runnable
对象,并且通过调用 .execute()
,我正在转换 Foo
-> Runnable
。鉴于我使用的是 ThreadFactory
,我预计会首先调用 ExampleFactory
,然后 execute()
将获取返回的对象。
我可以重载执行程序服务的
execute(Runnable)
方法以获得类似的 execute(Foo f)
,但这对于这个问题来说似乎有点矫枉过正?特别是因为我只会更改输入和返回类型,但会保留以前的功能?
不知道答案,但您是否尝试过查看
r
行之前的 if (! (r instanceof Foo)) {
的类型?
编辑:您可以使用
System.out.println(r.getClass())