[英]Java ExecutorService does not work as expected
我看了一下JAVA,並嘗試使用ExecutorService。 不幸的是,我的執行者沒有啟動我的可運行對象。 我正嘗試從存儲在文件列表中的不同XML文件中獲取一些信息。
FileFinder fileFinder = new FileFinder(path);
List<File>files = fileFinder.getFiles();
ExecutorService threadPool = Executors.newFixedThreadPool(configReader.getThreadcount(), new ThreadFactory() {
@Override
public Thread newThread(Runnable r) {
return new EinbucherThread();
}
});
for(File file : files)
{
System.out.println("Started working");
USEinbucher einbucher = new USEinbucher(file, verbindung);
threadPool.execute(einbucher);
}
threadPool.shutdown();
try {
while(!threadPool.awaitTermination(1, TimeUnit.SECONDS)) {
i++;
System.out.println("waiting "+i );
;
}
} catch (InterruptedException e) {
e.printStackTrace();
}
我以為可以通過將解組器放入線程來提高性能。 因此,我不需要為每個文件創建一個解組器,而是每個線程僅創建一次(據我了解的API,每個線程可以多次使用)。
public class EinbucherThread extends Thread {
private Unmarshaller um;
public EinbucherThread() {
try {
JAXBContext jb = JAXBContext.newInstance("klassen");
um = jb.createUnmarshaller();
System.out.println("Thread was created");
} catch (JAXBException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public Unmarshaller getUm() {
return um;
}
不幸的是,似乎從未達到我的可運行類的run方法。
public class USEinbucher implements Runnable {
private File lieferung;
private Verbindung verbindung;
public USEinbucher(File lieferung, Verbindung verbindung) {
this.lieferung=lieferung;
this.verbindung=verbindung;
}
@Override
public void run()
{
System.out.println("Started to work");
einbuchen();
}
我插入了一些println進行調試。 具有三個文件和兩個線程數,我的輸出如下所示:
開始工作
線程已創建
開始工作
線程已創建
開始工作
線程已創建
等待1
等待2
等待3…
任何解釋表示贊賞。
ThreadFactory.newThread應該返回一個負責運行參數Runnable
對象的Thread
。 考慮將Runnable
參數傳遞給您的Thread對象。 例如:
@Override
public Thread newThread(Runnable r) {
return new EinbucherThread(r);
}
//in the constructor of EinbucherThread
public EinbucherThread (Runnable r){
super(r);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.