在 Java 中,我得到一个强制转换异常:
java.lang.ClassCastException: java.util.concurrent.ThreadPoolExecutor$Worker
incompatible with com.myco.TaskListEntry
at com.myco.JobThreadFactory.newThread(JobThreadFactory.java:17)
这是代码:
public class JobThreadFactory implements ThreadFactory {
@Override
public Thread newThread(Runnable r) {
TaskListEntry entry = (TaskListEntry)r; //<== Cast exception!
return new Thread(r, "Thread for " + entry.toString());
}
}
@DisallowConcurrentExecution
public class WorksheetSessionJob implements Job {
private List<TaskListEntry> taskListEntries;
@Override
public void execute(JobExecutionContext jobContext) throws JobExecutionException {
ThreadFactory threadFactory = new JobThreadFactory();
ExecutorService executor = Executors.newCachedThreadPool(threadFactory);
for( TaskListEntry nextEntry : getWorkListEntries() ) {
executor.execute(nextEntry);
}
}
private List<TaskListEntry> getWorkListEntries() {
List<TaskListEntry> entries = new ArrayList<TaskListEntry>();
// TODO Get rows from DB - for now, make something up to test with
//-- beginning of fake data creation ----------
TaskListEntry entry = new TaskListEntry("0022", "04590150560", "DI_MODULAR", 1);
entries.add(entry);
entry = new TaskListEntry("0007", "04590150560", "DI_MODULAR", 2);
entries.add(entry);
//-- end of fake data creation ----------------
return entries;
}
}
public class TaskListEntry implements Runnable {
private String worksheetNumber;
private String specimenNumber;
private String instrumentName;
private int id;
public TaskListEntry(String worksheetNumber,
String specimenNumber, String instrumentName, int id) {
super();
this.worksheetNumber = worksheetNumber;
this.specimenNumber = specimenNumber;
this.instrumentName = instrumentName;
this.id = id;
}
@Override
synchronized public void run() {
// executor in my Job should have created a thread for me to run in
//-- TESTING ONLY -------------
try {
Thread.sleep(10000); //force execution to another thread?
} catch (InterruptedException e) {
e.printStackTrace();
}
//-- END OF TESTING -----------
}
}
为什么没有发送我的 TaskListEntry 可运行文件?我需要使用该类中的值来命名相应的线程。我究竟做错了什么?!