此代碼運行速度非常慢。我傾銷了這些線程,並且幾乎有一個線程正在同時運行,但是當我將ExecutorService
更改爲ForkJoinPool
時,代碼運行速度非常快。我不知道爲什麼線程都在等待,我的電腦有8個內核...線程正在等待ThreadPoolExecutor
public class Tests {
public static void main(String[] args) throws InterruptedException {
int NUM_OF_THREADS = 8;
int NUM_OF_INCREMENTS = 100_000_000;
//ExecutorService service = Executors.newWorkStealingPool();
ExecutorService service = Executors.newFixedThreadPool(NUM_OF_THREADS);
final Counter counter = new StupidCounter();
long before = System.currentTimeMillis();
for (int i = 0; i < NUM_OF_INCREMENTS; i++) {
service.submit(newCounterClient(counter, i));
}
service.shutdown();
service.awaitTermination(1, TimeUnit.MINUTES);
long end = System.currentTimeMillis();
System.out.println(end - before);
System.out.println(counter.getCounter());
}
static class CounterClient implements Runnable {
private Counter counter;
private int num;
public CounterClient(Counter counter, int num) {
this.counter = counter;
this.num = num;
}
@Override
public void run() {
counter.increment();
}
}
static interface Counter {
void increment();
long getCounter();
}
static class StupidCounter implements Counter {
long i = 0;
@Override
public void increment() {
i++;
}
@Override
public long getCounter() {
return i;
}
}
}
"pool-1-thread-7" #17 prio=5 os_prio=31 tid=0x00007faaa481c000 nid=0x6503 waiting on condition [0x0000700001d6d000]
java.lang.Thread.State: WAITING (parking)
at sun.misc.Unsafe.park(Native Method)
- parking to wait for <0x00000006c006b3d8> (a java.util.concurrent.locks.ReentrantLock$NonfairSync)
at java.util.concurrent.locks.LockSupport.park(LockSupport.java:175)
at java.util.concurrent.locks.AbstractQueuedSynchronizer.parkAndCheckInterrupt(AbstractQueuedSynchronizer.java:836)
at java.util.concurrent.locks.AbstractQueuedSynchronizer.doAcquireInterruptibly(AbstractQueuedSynchronizer.java:897)
at java.util.concurrent.locks.AbstractQueuedSynchronizer.acquireInterruptibly(AbstractQueuedSynchronizer.java:1222)
at java.util.concurrent.locks.ReentrantLock.lockInterruptibly(ReentrantLock.java:335)
at java.util.concurrent.LinkedBlockingQueue.take(LinkedBlockingQueue.java:439)
at java.util.concurrent.ThreadPoolExecutor.getTask(ThreadPoolExecutor.java:1067)
at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1127)
at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:617)
at java.lang.Thread.run(617Thread.java:745)