用java进行线程精加工测试

用java进行线程精加工测试,java,multithreading,Java,Multithreading,我有这个代码,我需要知道线程“th1”是否完成 因为我需要在这个线程之后执行一些操作。。 例如我需要打印消息时,从这个线程内完成主功能 public static void main(String[] args) { File folder=new File("E:/project_3/audio/"); File[] fileList=folder.listFiles(); for ( File file:fileList) { if(file.is

我有这个代码,我需要知道线程“th1”是否完成 因为我需要在这个线程之后执行一些操作。。 例如我需要打印消息时,从这个线程内完成主功能

public static void main(String[] args) {

    File folder=new File("E:/project_3/audio/");
    File[] fileList=folder.listFiles();
    for ( File file:fileList) {

        if(file.isFile()){
            System.out.println(file.getName());
            thread_reading th1=new thread_reading(file.getName());
            new Thread(th1).start();
        }
    }

}

我想你可以使用join:

Thread th1 = new Thread(th1);
th1.start();
... more code...
th1.join();

为了最大限度地并行处理音频文件,我将此算法分为两部分:

  • 首先,读取目录以查找要处理的文件,并将它们存储在列表或数组中。这将允许您准确地知道必须处理多少个文件(对于下面的技术建议很有用)
  • 然后,对于找到的每个文件,启动一个线程,通过
    threading
    作业对其进行处理
为了在处理完所有文件后得到通知,我将使用倒计时闩锁。每个线程都会调用
倒计时()
,告诉它已经完成;主线程只需等待N个完成信号

以下是主要代码:

// 1. Gather files
//File folder = new File("E:/project_3/audio/");
File[] fileList = folder.listFiles(new FileFilter() {
    @Override
    public boolean accept(File pathname) {
        return pathname.isFile();
    }
});

// 2. Process the files in parallel
CountDownLatch completionCounter = new CountDownLatch(fileList.length);
for (File file : fileList) {
    System.out.println(file.getName());
    thread_reading th1 = new thread_reading(file.getName(), completionCounter);
    new Thread(th1).start();
}

// 3. Wait for all processes to finish
try {
    completionCounter.await();
} catch (InterruptedException e) {
    e.printStackTrace();
}
下面是
线程读取作业的代码:

public class thread_reading implements Runnable {

    private final String name;
    private final CountDownLatch completionCounter;

    public thread_reading(String name, CountDownLatch completionCounter) {
        this.name = name;
        this.completionCounter = completionCounter;
    }

    @Override
    public void run() {
        // ... do stuff ...
        System.out.println(name);

        // Say it's done
        completionCounter.countDown();
    }
}

您可以尝试创建一个执行器并在那里添加您的Runnable,然后等待它们终止

//设置要并行运行的线程数
ExecutorService executor=Executors.newFixedThreadPool(5);
用于(文件:文件列表){
if(file.isFile()){
System.out.println(file.getName());
thread_reading th1=新线程_reading(file.getName());
执行人提交(th1);
}
}
executor.shutdown();
试一试{
执行器等待终止(长最大值,时间单位纳秒);
}捕捉(中断异常e){
//等等
}

如果流程暂停以完成线程,为什么需要创建线程而不是简单地在主线程上执行相同的逻辑?这里有一个很好的答案,您可以分享
线程读取的代码吗?如果它是一个
Runnable
,那么您可以在它的
run
方法的末尾执行
System.out
。如果您想在线程上使用完成语义,请使用Future。有了这个解决方案,使用线程没有意义,因为文件的处理将被序列化。技术上有效,但毫无用处:)不正确,您可以在当前线程的start()和join()之间并行执行大量工作。如果您调用
start()
,然后立即在循环内部调用
join()
,进程将被序列化。要使解决方案正常工作,需要将所有线程存储在某个列表中,全部启动,然后循环调用
join()