Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>The <a href="http://www.youtube.com/watch?v=iV2ViNJFZC8" rel="nofollow">Ministry of Silly Walks</a> further recommends the following multi-threaded alternative:</p> <pre><code>package test; import java.util.concurrent.*; import java.util.concurrent.atomic.AtomicInteger; public class Test { private static final int NUMBER_WALKS = 100; private static final int NUMBER_STEPS = 500; private static class Counter implements Runnable { private final AtomicInteger counter; private final ConcurrentSkipListMap&lt;Integer, Integer&gt; totals; public Counter(final AtomicInteger counter, final ConcurrentSkipListMap&lt;Integer, Integer&gt; totals) { this.counter = counter; this.totals = totals; } @Override public void run() { int result; Integer oldValue; while ((Thread.currentThread().isInterrupted() == false) &amp;&amp; (this.counter.decrementAndGet() &gt;= 0)) { result = 0; for (int i = 0; i &lt; NUMBER_STEPS; ++i) { result += ThreadLocalRandom.current().nextInt(2) == 0 ? -1 : 1; } oldValue = totals.putIfAbsent(result, 1); if (oldValue != null) { while (totals.replace(result, oldValue, oldValue + 1) == false) { oldValue = totals.get(result); } } } } } public static void main(String[] args) throws ExecutionException, InterruptedException { final AtomicInteger counter = new AtomicInteger(NUMBER_WALKS); final ConcurrentSkipListMap&lt;Integer, Integer&gt; totals = new ConcurrentSkipListMap&lt;&gt;(); final int numCPUs = Runtime.getRuntime().availableProcessors(); final ExecutorService executor = Executors.newFixedThreadPool(numCPUs); for (int i = 0; i &lt; numCPUs; ++i) { executor.submit(new Counter(counter, totals)); } executor.shutdown(); if (executor.awaitTermination(10, TimeUnit.SECONDS)) { for (Integer key : totals.keySet()) { System.out.println(String.format("%3d was called %3d times.", key, totals.get(key))); } } else { executor.shutdownNow(); System.err.println("Executor did not terminate as expected."); } } } </code></pre>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload