When you have two things that must happen at the same time or
unpredictably, the normal Java paradigm is to use a thread for each.
We will discuss threads in detail in Chapter 24,
but for now, just think of a thread as a small, semi-independent flow
of control within a program, just as a program is a small,
self-contained flow of control within an operating system. The Thread
API requires you to construct a method whose signature is
public
void
run( )
to do the body of work for the thread,
and call the start( )
method of the thread to
“ignite” it and start it running independently. This
example creates a Thread
subclass called
DataThread
, which reads from one file and writes
to another.
DataThread
works a byte at a time so that it
will work correctly with interactive prompts, which don’t end
at a line ending. My now-familiar converse( )
method creates two of these
DataThreads
, one to handle data
“traffic” from the keyboard to the remote, and one to
handle bytes arriving from the remote and copy them to the standard
output. For each of these the start( )
method is
called. Example 11-9 shows the
entire program.
Example 11-9. CommPortThreaded.java
import java.io.*; import javax.comm.*; import java.util.*; /** * This program tries to do I/O in each direction using a separate Thread. */ public class CommPortThreaded extends CommPortOpen { public static void main(String[] ap) throws IOException, NoSuchPortException,PortInUseException, UnsupportedCommOperationException { CommPortThreaded cp; try { cp = new CommPortThreaded( ); cp.converse( ); } catch(Exception e) { System.err.println("You lose!"); System.err.println(e); } } public CommPortThreaded( ) throws IOException, NoSuchPortException, PortInUseException, UnsupportedCommOperationException { super(null); } /** This version of converse( ) just starts a Thread in each direction. */ protected void converse( ) throws IOException { String resp; // the modem response. new DataThread(is, System.out).start( ); new DataThread(new DataInputStream(System.in), os).start( ); } /** This inner class handles one side of a conversation. */ class DataThread extends Thread { DataInputStream inStream; PrintStream pStream; /** Construct this object */ DataThread(DataInputStream is, PrintStream os) { inStream = is; pStream = os; } /** A Thread's run method does the work. */ public void run( ) { byte ch = 0; try { while ((ch = (byte)inStream.read( )) != -1) pStream.print((char)ch); } catch (IOException e) { System.err.println("Input or output error: " + e); return; } } } }
3.15.34.39