同时运行多个线程

时间:2014-09-10 17:53:20

标签: java multithreading

请帮帮我。我想一次从数组中运行所有线程

public class Main {
    public static void main(String[] args) {
        String [] folders = (new counter()).readfile();
        Thread[] threads = new Thread[folders.length];
        for (int i = 0; i < folders.length; i++) {
            threads[i] = new Thread(new MyThread(folders[i]));
        }
        startThreads(threads);
    }

    private static void startThreads(Thread[] threads) {
        for (Thread t : threads)
            t.start();
    }
}

其他使用Executors,但在这种情况下我有n个穿线器,它们互相等待。 http://joxi.ru/b6AQVP3JTJBmfbW41MA

 String [] folders = (new counter()).readfile();
    Thread[] threads = new Thread[folders.length];
    int size= folders.length;

    for (int i = 0; i < folders.length; i++) {
        threads[i] = new Thread(new MyThread(folders[i]));
    }
    ExecutorService executor = Executors.newFixedThreadPool(folders.length);
    for (int i = 0; i < size; i++) {
        Runnable worker = new MyThread(folders[i]);
        executor.execute(worker);
    }
    executor.shutdown();
    while (!executor.isTerminated()) {
    }
    System.out.println("Finished all threads");

0 个答案:

没有答案