Java Reference
In-Depth Information
Running Code in a Different Thread
Problem
You need to write a threaded application.
Solution
Write code that implements Runnable ; instantiate and start it.
Discussion
There are several ways to implement threading, and they all require you to implement the
Runnable interface. Runnable has only one method, whose signature is:
public void run( );
You must provide an implementation of the run() method. When this method returns, the
thread is used up and can never be restarted or reused. Note that there is nothing special in
the compiled class file about this method; it's an ordinary method and you could call it your-
self. But then what? There wouldn't be the special magic that launches it as an independent
flow of control, so it wouldn't run concurrently with your main program or flow of control.
For this, you need to invoke the magic of thread creation.
One way to do this is simply to subclass from java.lang.Thread (which also implements
this interface; you do not need to declare redundantly that you implement it). This approach
is shown in Example 22-1 . Class ThreadsDemo1 simply prints a series of “Hello from X” and
“Hello from Y” messages; the order in which they appear is indeterminate because there is
nothing in either Java or the program to determine the order of things.
Example 22-1. ThreadsDemo1.java
public
public class
class ThreadsDemo1
ThreadsDemo1 extends
extends Thread {
private
private String mesg ;
private
private int
int count ;
/** Run does the work: print a message, "count" number of times */
public
public void
void run () {
while
while ( count -- > 0 ) {
System . out . println ( mesg );
Search WWH ::




Custom Search