繁体   English   中英

如何维护线程列表?

[英]how to maintain a list of threads?

我有数百个文件要处理。 我一次只做一个文件,需要30分钟。

我想我可以同时在10个线程中进行此处理,一次处理10个文件,而且我可能能够在3分钟而不是30分钟内完成此处理。

我的问题是,管理我的10个线程的“正确”方法是什么? 完成后,创建一个新的,最大数量为10。

这就是我到目前为止所拥有的...这是“正确”的方法吗?

public class ThreadTest1 {

    public static int idCounter = 0;

    public class MyThread extends Thread {

        private int id;

        public MyThread() {
            this.id = idCounter++;
        }

        public void run() {
                    // this run method represents the long-running file processing
            System.out.println("I'm thread '"+this.id+"' and I'm going to sleep for 5 seconds!");
            try {
                Thread.sleep(5000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            System.out.println("I'm thread '"+this.id+"' and I'm done sleeping!");
        }

    }

    public void go() {

        int MAX_NUM_THREADS = 10;

        List<MyThread> threads = new ArrayList<MyThread>();

            // this for loop represents the 200 files that need to be processed
        for (int i=0; i<200; i++) {

            // if we've reached the max num of threads ...
            while (threads.size() == MAX_NUM_THREADS) {
                // loop through the threads until we find a dead one and remove it
                for (MyThread t : threads) {
                    if (!t.isAlive()) {
                        threads.remove(t);
                        break;
                    }
                }

            }

            // add new thread
            MyThread t = new MyThread();
            threads.add(t);
            t.start();

        }

    }

    public static void main(String[] args) {
        new ThreadTest1().go();
    }

}

您可以使用ExecutorService来管理线程。

您可以while线程运行方法中添加while循环,以重复执行文件处理任务。 您也可以阅读有关BlockingQueue的用法。 我认为在线程之间分配新文件(任务)非常合适。

如果您愿意,我建议您使用Camel的File组件 该组件将并发处理所有问题,以确保多个线程不会尝试处理同一文件。 使代码成为多线程的最大挑战是确保线程不交互。 让框架为您解决这个问题。

例:

 from("file://incoming?maxMessagesPerPoll=1&idempotent=true&moveFailed=failed&move=processed&readLock=none")
       .threads(10).process() 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM