LinkedIn Interview Question

Java: how do you make n threads run at the same time?

Interview Answers

Anonymous

Jan 15, 2011

weird question - threads do run at the same time, unless you do something special to prevent it. this code makes threads run at the same time: for (int i = 0; i < n; ++i) new Thread().start(); the answer posted by Anonymous is to a different question - how to synchronize certain parts of threads (that do run at the same time :). This is very legit question and CountDownLatch / CyclicBarrier are standard mechanisms to achieve that

3

Anonymous

Feb 16, 2011

Ugh, how about using ExecutorService and creating a fixed sized pool. That ensures that only a maximum of pool size threads run at a given time.

1

Anonymous

Mar 14, 2011

1. In the main thread we can create an instance of java.util.concurrent.CyclicBarrier class using the constructor Barrier b = CyclicBarrier(n); 2. Then each thread in their first line do b.await(), All threads until n of them have called it will block on this call 3. When the last thread does b.await() all of them will move past this call;

1

Anonymous

Aug 21, 2012

Simple answer would be fixed size threadpool.This type of pool always has a specified number of threads running; if a thread is somehow terminated while it is still in use, it is automatically replaced with a new thread.

Anonymous

Dec 1, 2010

Actually, there are needs for multiple threads to run at the same time, so the system can waiting for all parties are ready before start. For example, if we want to measure how long the tests take when all threads run "Concurrently' (see the example in the book "Java Concurrent in Practice" by Brian Goetz etc. The join only works for waiting 1 thread. If you have 5-10 threads, join is not the good option. You can use CountDownLatch as gate or CyclicBarrier for this purpose. Here is the example from the above mentioned book. public long timeTasks(int nThreads, final Runnable task) throws InterruptedException { final CountDownLatch startGate = new CountDownLatch(1); final CountDownLatch endtGate = new CountDownLatch(nThreads); for (int i = 0; i < nThreads; i++) { Thread t = new Thread() { public void run() { try { startGate.await(); try { task.run(); } finally { endtGate.countDown(); } } catch (InterruptedException ignored) {} } }; t.start(); } long start = System.nanoTime(); startGate.countDown(); endtGate.await(); long end = System.nanoTime(); return end-start; }

2

Anonymous

May 20, 2010

I think it defeats the purpose of having threads. Why would you want that? Anyway, the correct answer is using join.

1