Reading and Writing: Threads

Problem

After the connection is made, you don’t know what order to read or write in.

Solution

Use a thread to handle each direction.

Discussion

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 ...

Get Java Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.