Name: Multi-threaded application
Points: 3
Type: Solitaire assignment. Everybody solves it alone!
Write a simple program which spawns 3 threads. These threads cooperate on generating numbers from 0 to 50 and printing them on standard output in the following form:
Thread 1: 0 Thread 1: 1 Thread 3: 2 Thread 2: 3 ... Thread 3: 49 Thread 1: 50
Please keep in mind the following facts when dealing with the solution:
Thread
but implement the Runnable
interface instead in your solution.Thread.currentThread().getName()
for obtaining the thread name.waitActively(50L, TimeUnit.MILLISECONDS)
, where the method body looks like this:
private static void waitActively(long duration, TimeUnit timeUnit) { long durationNanos = timeUnit.toNanos(duration); long start = System.nanoTime(); while ((System.nanoTime() - start) < durationNanos); }NOTE: Active wait loop is an exceptional instrument and should never be used under normal circumstances as it wastes CPU time and therefore has negative impact on the overall performance. However, in this particular case it is satisfactory as the standard way of waiting for a specified time e.g.
Thread.sleep()
would have caused context switch and therefore
masked off many possible synchronization mistakes.
No matter how much actively you wait in your solution, there is no guarantee that you avoided all synchronization
mistakes. Active wait loop only increases the chance that synchronization mistakes manifest themselves early.