gpt4 book ai didi

Java ExecutorService 未按预期工作

转载 作者:行者123 更新时间:2023-12-02 03:23:34 25 4
gpt4 key购买 nike

我查看了 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);
}

关于Java ExecutorService 未按预期工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39300068/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com