我正在try 使用自定义ThreadFactory
实现,它允许我使用自定义对象而不是通用Runnable
对象.
以下是我所能提供的最小例子.除了为我的问题创建一个功能框架之外,Foo()
类定义和Main()
在很大程度上无关紧要.我正在使用ExecutorService
的execute()
方法来调用我的ExampleFactory
.这个问题很大程度上与通过ExecutorService
调用过载的ThreadFactory
的正确利用有关.代码后面的上下文.
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()
将接收返回的对象.
我可以超载Executor Service的execute(Runnable)
方法以获得类似的execute(Foo f)
,但对于这个问题来说这似乎有些矫枉过正吗?特别是因为我只会更改输入和返回类型,但会保留以前的功能?