【问题标题】:Java ExecutorService does not work as expectedJava ExecutorService 无法按预期工作
【发布时间】:2023-03-24 19:35:01
【问题描述】:

我查看了 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…

感谢任何解释。

【问题讨论】:

  • newThread有一个参数Runnable,返回的线程负责运行
  • Object.wait 需要在循环中执行,但没有必要使用 ExecutorService.awaitTermination 执行此操作。一个awaitTermination(Long.MAX_VALUE, TimeUnit.MILLISECONDS) 电话就足够了。

标签: java executorservice


【解决方案1】:

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);
}

【讨论】:

  • 感谢您的快速解决方案。现在它按预期工作
猜你喜欢
  • 1970-01-01
  • 2022-10-21
  • 2018-04-20
  • 2023-03-05
  • 1970-01-01
  • 2013-12-23
  • 2014-12-09
  • 2016-01-13
  • 2020-09-21
相关资源
最近更新 更多