线程数组与执行程序服务?

时间:2018-04-23 17:27:56

标签: java concurrency

我是Java的并发新手,但我在理解执行器服务的工作方面遇到了问题。

我的问题:我分别执行下面的代码,我想知道线程数组比执行服务更快(3s vs 30s,System.currentTimeMillis())。

public class SimpleExample {
private static final int THREAD_COUNT = 10;
private final AtomicInteger cnt;

private SimpleExample() {
    cnt = new AtomicInteger();
    cnt.set(0);
}

public static void main(String[] args) throws IOException, InterruptedException {
    // threads();
    // service();
}

private static void threads() throws InterruptedException {
    SimpleExample example = new SimpleExample();
    ParallelTask task = new ParallelTask(example);
    Thread[] threads = new Thread[THREAD_COUNT];
    for (int i = 0; i < threads.length; i++) {
        threads[i] = new Thread(task);
    }

    long a = System.currentTimeMillis();
    for (Thread thread : threads) {
        thread.start();
    }

    for (Thread thread : threads) {
        thread.join();
    }
    System.out.println("time: " + (System.currentTimeMillis() - a));
}

private static void service() {
    SimpleExample example = new SimpleExample();
    ParallelTask task = new ParallelTask(example);
    ExecutorService service = Executors.newFixedThreadPool(THREAD_COUNT);

    long a = System.currentTimeMillis();
    Future future = service.submit(task);
    while (!future.isDone()) {
        // do nothing
    }
    service.shutdown();
    System.out.println("time: " + (System.currentTimeMillis() - a));
}

void run() {
    while (cnt.get() < 300) {
        try {
            Thread.sleep(100);
            System.out.println(cnt.get());
            cnt.incrementAndGet();
        } catch (InterruptedException ignore) {}
    }
}

static class ParallelTask implements Runnable {
    private final SimpleExample example;

    ParallelTask(SimpleExample example) {
        this.example = example;
    }

    @Override
    public void run() {
        example.run();
    }
}

}

怎么可能? 感谢。

0 个答案:

没有答案