对于我的论文,我正在研究离散事件系统模拟器。模拟包含一组,SimulatorThread extends Thread其动作在于Event将 s 调度到Simulator. 每一个都通过 与SimulatorThread交互。SimulatorSimulatorInterface
public abstract class SimulatorThread extends Thread {
private SimulatorInterface si;
public SimulatorThread(SimulatorInterface si) {
this.si = si;
}
...
}
public final class Simulator {
private ExecutorService exec;
...
public void assignThread(SimulatorThread... stList) {
...
}
}
在模拟开始之前,每个都SimulatorThread被分配给Simulator,然后Simulator将通过 执行每个线程exec.execute(simulatorThread)。我的问题是,在代码的某些部分中,我需要获取对当前正在运行的引用SimulatorThread,但是该指令(SimulatorThread) Thread.currentThread()给出了强制转换执行。事实上的输出System.out.print(Thread.currentThread().getClass())是class java.lang.Thread,但我希望输出是class SimulatorThread可以通过使用指令simulatorThread.start()而不是使用执行程序运行线程来获得的。所以我认为问题在于编写一个 ThreadFactory返回SimulatorThread.
事实上,我尝试使用琐碎的SimulatorThreadFactory extends ThreadFactory:
public class SimulatorThreadFactory implements ThreadFactory {
@Override
public Thread newThread(Runnable r) {
return new SimulatorThread(new SimulatorInterface());
}
}
有了这个,我获得了前面引用的输出“类 SimulatorThread”。问题是当我调用'exec.execute(simulatorThread)'时,参数有一个我需要访问的属性'SimulatorInterface',但我不能因为方法'newThread'的参数是'Runnable '。我在这里公开了一个错误的代码,我希望它比我用文字解释的方式更好地表达了我的意思:
public class SimulatorThreadFactory implements ThreadFactory {
@Override
public Thread newThread(Runnable r) {
SimulatorInterface si = r.getSimulatorInterface(); // this is what
// I would like
// the thread factory
// to do
return new SimulatorThread(si);
}
}
那么,如果它的参数是 a ,我如何访问方法内的“SimulatorThread”的属性“SimulatorInterface”newThread以创建a ?SimulatorThreadRunnable