Compute and display elapsed time of an operation

Sometimes you want to compute the time a certain operation takes, which can be done by using the currentTimeMillis() method of the System class.
The value returned is the current time in milliseconds and by calling the method before and after the operation you can compute the difference in time,
which is the time of the operation.
The example below performs and operation by looping from 0 to 9 and in each loop makes the thread sleep for 60 milliseconds and then displays the time elapsed
between the start and the end of this operation.

Continue reading

Setting thread priorities

Setting a threads priority can be very useful if one thread has more critical tasks to perform than another.
The Thread class has a method called setPriority(int level) with which you can alter the priority a Thread instance has.
The priority level range from 1 (least important) to 10 (most important) and if no level is explicitly set, a Thread instance has the priority level of 5.
In the first example below no priorites are set, so both threads have the priority level 5. The TestThread class implements the Runnable interface and in its
run() method loops from 1 to 10 and output the number along with its Thread id, which is passed to the constructor.

Continue reading