使用java进行线程完成测试

时间:2015-04-16 19:16:18

标签: 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.isFile()){
            System.out.println(file.getName());
            thread_reading th1=new thread_reading(file.getName());
            new Thread(th1).start();
        }
    }

}

3 个答案:

答案 0 :(得分:4)

我认为你可以使用join:

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

https://docs.oracle.com/javase/7/docs/api/java/lang/Thread.html#join%28long%29

答案 1 :(得分:0)

为了最大化音频文件处理的并行化,我将把这个算法分成两部分:

  • 首先,读取目录以查找要处理的文件,并将它们存储在List或数组中。这样可以确切地知道必须处理多少文件(对于下面的技术建议很有用)。
  • 然后,对于找到的每个文件,启动一个线程以使用thread_reading作业处理它。

要在处理完所有文件后收到通知,我会使用CountDownLatch。每个线程都会调用countdown()来告诉它已经完成;并且主线程必须等待那些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();
}

以下是thread_reading职位的代码:

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

答案 2 :(得分:0)

你可以尝试创建一个执行器并在那里添加你的runnables并等待它们终止

//Set how many threads you want to run in parallel
ExecutorService executor = Executors.newFixedThreadPool(5);
for (File file: fileList) {
  if (file.isFile()) {
    System.out.println(file.getName());
    thread_reading th1 = new thread_reading(file.getName());
    executor.submit(th1);
  }
}
executor.shutdown();
try {
  executor.awaitTermination(Long.MAX_VALUE, TimeUnit.NANOSECONDS);
} catch (InterruptedException e) {
  //wait
}