站内搜索: 请输入搜索关键词
当前页面: 图书首页 > Java Threads, Third Edition

2.7 Summary - Java Threads, Third Edition

Previous Section  < Day Day Up >  Next Section

2.7 Summary

In this chapter, we've had our first taste of threads. We've learned that threads are separate tasks executed by a single program. This is the key to thinking about how to design a good multithreaded program: what logical tasks make up your program? How can these tasks be separated to make the program logic easier, or benefit your program by running in parallel? In our case, we have two simple tasks: display a random character and display the key that a user types in response. In later chapters, we add more tasks (and more threads) to this list.

At a programming level, we've learned how to construct, start, pause, and stop threads. We've also learned about the Runnable interface and how that interface allows us a great degree of flexibility in how we develop the class hierarchy for our objects. Tasks can be either Thread objects or Runnable objects associated with a thread. Using the Runnable interface allows more flexibility in how you define your tasks, but both approaches have merit in different situations.

We've also touched on how threads interoperate by calling methods on the same object. The ability of threads to interoperate in this manner includes the ability for them to share data as well as code. That data sharing is key to the benefits of a multithreaded program, but it carries with it some pitfalls. This is covered in the next chapter.

2.7.1 Example Classes

Here are the class names and Ant targets for the examples in this chapter:

Description

Main Java class

Ant target

Factorial Example

javathreads.examples.ch02.example1.Factorial number

ch2-ex1

First Swing Type Tester

javathreads.examples.ch02.example2.SwingTypeTester

ch2-ex2

Type Tester (with Stop button)

javathreads.examples.ch02.example3.SwingTypeTester

ch2-ex3

Type Tester (uses interrupt() method)

javathreads.examples.ch02.example4.SwingTypeTester

ch2-ex4

Type Tester (uses Runnable interface)

javathreads.examples.ch02.example5.SwingTypeTester

ch2-ex5

Type Tester (Runnable and interrupt())

javathreads.examples.ch02.example6.SwingTypeTester

ch2-ex6

Type Tester (animated display)

javathreads.examples.ch02.example7.SwingTypeTester

ch2-ex7


The factorial program accepts a command-line argument to indicate the integer whose factorial should be calculated; that can be set with this Ant property:

<property name="FactorialArg" value="10"/>

    Previous Section  < Day Day Up >  Next Section