O'Reilly logo

Java Cookbook by Ian F. Darwin

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required