Java Reference
In-Depth Information
The output from the above lines would be:
Thread-0
namedThread
Note that the name of the variable holding the address of a thread is not the same
as the name of the thread! More often than not, however, we do not need to know
the latter.
Method sleep is used to make a thread pause for a specifi ed number of millisec-
onds. For example:
myThread.sleep(1500); //Pause for 1.5 seconds.
This suspends execution of the thread and allows other threads to be executed.
When the sleeping time expires, the sleeping thread returns to a ready state, waiting
for the processor.
Method interrupt may be used to interrupt an individual thread. In particular, this
method may be used by other threads to 'awaken' a sleeping thread before that
thread's sleeping time has expired. Since method sleep will throw a checked excep-
tion (an InterruptedException ) if another thread invokes the interrupt method, it
must be called from within a try block that catches this exception.
In the next example, static method random from core class Math is used to gener-
ate a random sleeping time for each of two threads that simply display their own
names ten times. If we were to run the program without using a randomising ele-
ment, then it would simply display alternating names, which would be pretty tedious
and would give no indication that threads were being used. Method random returns
a random decimal value in the range 0-0.999…, which is then multiplied by a scaling
factor of 3000 and typecast into an int , producing a fi nal integer value in the range
0-2999. This randomising technique is also used in later thread examples, again in
order to avoid producing the same pattern of output from a given program.
Note the use of extends Thread in the opening line of the class. Though this class
already implements the Runnable interface (and so has a defi nition of method run ),
the default implementation of run does nothing and must be overridden by a defi ni-
tion that we supply.
Example
public class ThreadShowName extends Thread
{
public static void main (String[] args)
{
ThreadShowName thread1, thread2;
thread1 = new ThreadShowName();
thread2 = new ThreadShowName();
thread1.start(); //Will call run .
thread2.start(); //Will call run .
}
Search WWH ::




Custom Search