Добавил:
Upload Опубликованный материал нарушает ваши авторские права? Сообщите нам.
Вуз: Предмет: Файл:

AhmadLang / Java, How To Program, 2004

.pdf
Скачиваний:
626
Добавлен:
31.05.2015
Размер:
51.82 Mб
Скачать

thread synchronization

timed waiting state

timeslice

unlock method of interface Lock

wait method of class Object

waiting state

[Page 1103 (continued)]

Self-Review Exercises

23.1 Fill in the blanks in each of the following statements:

a.C and C++ are ___________ -threaded languages, whereas Java is a(n)

___________ -threaded language.

[Page 1104]

b.A thread enters the terminated state when ___________.

c.To pause for a designated number of milliseconds and resume execution, a thread should call method ___________.

d.Method ___________ of class Condition moves a single thread in an object's waiting state to the runnable state.

e.Method ___________ of class Condition moves every thread in an object's waiting state to the runnable state.

f.A(n) ___________ thread enters the ___________ state when it completes its task or otherwise terminates.

g.A runnable thread can enter the ___________ state for a specified interval of time.

h.At the operating-system level, the runnable state actually encompasses two separate states, ___________ and ___________.

i.Runnables are executed using a class that implements the ___________

interface.

j. ExecutorService method ___________ ends each thread in an ExecutorService as soon as it finishes executing its current Runnable, if any.

k.A thread can call method ___________ on a Condition object to release the associated Lock and place that thread in the ___________ state.

l.In a(n) ___________ relationship, the ___________ portion of an application generates data and stores it in a shared object, and the __________ portion of an application reads data from the shared object.

m.To minimize the amount of waiting time for threads that share resources and operate at the same average speeds, use a(n) ___________.

n.Class ___________ implements the BlockingQueue interface using an array.

o.The keyword ___________ indicates that only one thread at a time should execute on an object.

23.2 State whether each of the following is true or false. If false, explain why.

a.A thread is not runnable if it is dead.

b.In Java, a higher-priority runnable thread should preempt threads of lower priority.

c.Some operating systems use timeslicing with threads. Therefore, they can enable threads to preempt threads of the same priority.

d.When the thread's quantum expires, the thread returns to the running state

as the operating system assigns the thread to a processor.

e.Without timeslicing, each thread in a set of equal-priority threads runs to completion before other threads of equal priority get a chance to execute.

[Page 1104 (continued)]

Answers to Self-Review Exercises

23.1 a) single, multi. b) its run method ends. c) THRead.sleep. d) signal. e) signalAll. f) runnable, terminated. g) timed waiting. h) ready, running. i) Executor. j) shutdown. k) await, waiting. l) producer/consumer, producer, consumer. m) circular

buffer. n) ArrayBlockingQueue. o) synchronized.

23.2 a) True. b) True. c) False. Timeslicing allows a thread to execute until its timeslice (or quantum) expires. Then other threads of equal priority can execute. d) False. When a thread's quantum expires, the thread returns to the ready state and the operating system assigns to the processor another thread. e) True.

[Page 1104 (continued)]

Exercises

23.3State whether each of the following is true or false. If false, explain why.

a.Method sleep does not consume processor time while a thread sleeps.

[Page 1105]

b.Using a Lock guarantees that deadlock cannot occur.

c.Once a Lock has been obtained by a thread, the Lock object will not allow another thread to obtain the lock until the first thread releases it.

d.Swing components are thread safe.

23.4Define each of the following terms.

a.thread

b.multithreading

c.runnable state

d.timed waiting state

e.preemptive scheduling

f.Runnable interface

g.signal method of class Condition

h.producer/consumer relationship

i.quantum

23.5Discuss each of the following terms in the context of Java's threading mechanisms:

a.Lock

b.producer

c.consumer

d.await

e.signal

f.Condition

23.6Two problems that can occur in systems like Java, that allow threads to wait, are deadlock, in which one or more threads will wait forever for an event that cannot occur, and indefinite postponement, in which one or more threads will be delayed for some unpredictably long time. Give an example of how each of these problems can occur in a multithreaded Java program.

23.7

23.8 Discuss the difference between Condition method await with no arguments and

Condition method await with a time-interval argument. In particular, what states do threads enter, and how can those threads return to the runnable state?

23.9Name three threads that are created automatically by the Java virtual machine and discuss the purpose of each thread.

23.10Write a program that bounces a blue ball inside a JPanel. The ball should begin moving with a mousePressed event. When the ball hits the edge of the JPanel, it should bounce off the edge and continue in the opposite direction. The ball should be updated using a Runnable.

23.11Modify the program in Exercise 23.10 to add a new ball each time the user clicks the mouse. Provide for a minimum of 20 balls. Randomly choose the color for each new ball.

23.12Modify the program in Exercise 23.11 to add shadows. As a ball moves, draw a solid black oval at the bottom of the JPanel. You may consider adding a 3-D effect by increasing or decreasing the size of each ball when it hits the edge of the JPanel.

23.13Modify the program in Exercise 23.11 or Exercise 23.12 to bounce the balls off each other when they collide. A collision should occur between two balls when the distance between the centers of those two balls is less than the sum of the two balls' radii.

[Page 1106]

Chapter 24. Networking

If the presence of electricity can be made visible in any part of a circuit, I see no reason why intelligence may not be transmitted instantaneously by electricity.

Samuel F. B. Morse

Protocol is everything.

Francois Giuliani

What networks of railroads, highways and canals were in another age, the networks of telecommunications, information and computerization ... are today.

Bruno Kreisky

The port is near, the bells I hear, the people all exulting.

Walt Whitman

OBJECTIVES

In this chapter you will learn:

To understand Java networking with URLs, sockets and datagrams.

To implement Java networking applications by using sockets and datagrams.

To understand how to implement Java clients and servers that communicate with one another.

To understand how to implement network-based collaborative applications.

To construct a multithreaded server.

[Page 1107]

Outline

24.1 Introduction

24.2 Manipulating URLs

24.3 Reading a File on a Web Server

24.4 Establishing a Simple Server Using Stream Sockets

24.5 Establishing a Simple Client Using Stream Sockets

24.6 Client/Server Interaction with Stream Socket Connections

24.7 Connectionless Client/Server Interaction with Datagrams

24.8 Client/Server Tic-Tac-Toe Using a Multithreaded Server

24.9 Security and the Network

24.10 Case Study: DeitelMessenger Server and Client

24.10.1 DeitelMessengerServer and Supporting Classes

24.10.2 DeitelMessenger Client and Supporting Classes

24.11 Wrap-Up

Summary

Terminology

Self-Review Exercises

Answers to Self-Review Exercises

Exercises

[Page 1107 (continued)]

24.1. Introduction

There is much excitement about the Internet and the World Wide Web. The Internet ties the information world together. The World Wide Web makes the Internet easy to use and gives it the flair and sizzle of multimedia. Organizations see the Internet and the Web as crucial to their information-systems strategies. Java provides a number of built-in networking capabilities that make it easy to develop Internet-based and Web-based applications. Java can enable programs to search the world for information and to collaborate with programs running on other computers internationally, nationally or just within an organization. Java can enable applets and applications to communicate with one another (subject to security constraints).

Networking is a massive and complex topic. Computer science and computer engineering students will typically take a full-semester, upper-level course in computer networking and continue with further study at the graduate level. Java is often used as an implementation vehicle in computer networking courses. In Java How to Program, Sixth Edition, we introduce a portion of Java's networking concepts and capabilities. We discuss more advanced networking capabilities in our book Advanced Java 2 Platform How to Program.

Java's fundamental networking capabilities are declared by classes and interfaces of package

java.net, through which Java offers stream-based communications that enable applications to view networking as streams of data. The classes and interfaces of package java.net also offer packetbased communications for transmitting individual packets of informationcommonly used to transmit audio and video over the Internet. In this chapter, we show how to create and manipulate sockets and how to communicate with packets and streams of data.

Our discussion of networking focuses on both sides of the client-server relationship. The client requests that some action be performed, and the server performs the action and responds to the client. A common implementation of the request-response model is between Web browsers and Web servers. When a user selects a Web site to browse through a browser (the client application), a request is sent to the appropriate Web server (the server application). The server normally responds to the client by sending an appropriate HTML Web page.

[Page 1108]

We introduce Java's socket-based communications, which enable applications to view networking as if it were file I/Oa program can read from a socket or write to a socket as simply as reading from a file or writing to a file. The socket is simply a software construct that represents one endpoint of a connection. We show how to create and manipulate stream sockets and datagram sockets.

With stream sockets, a process establishes a connection to another process. While the connection is in place, data flows between the processes in continuous streams. Stream sockets are said to provide a connection-oriented service. The protocol used for transmission is the popular TCP (Transmission Control Protocol).

With datagram sockets, individual packets of information are transmitted. This is not appropriate for everyday programmers, because the protocol usedUDP, the User Datagram Protocolis a connectionless service, and thus does not guarantee that packets arrive in any particular order. With UDP, packets can even be lost or duplicated. Significant extra programming is required on the programmer's part to deal with these problems (if the programmer chooses to do so). UDP is most appropriate for network applications that do not require the error checking and reliability of TCP. Stream sockets and the TCP protocol will be more desirable for the vast majority of Java programmers.

Performance Tip 24.1

Connectionless services generally offer greater performance but less reliability than connection-oriented services.

Portability Tip 24.1

TCP, UDP and related protocols enable a great variety of heterogeneous computer systems (i.e., computer systems with different processors and different operating systems) to intercommunicate.

The chapter includes a case study in which we implement a client/server chat application similar to the instant-messaging services popular on the Web today. The application incorporates many networking techniques introduced in this chapter. It also introduces multicasting, in which a server can publish information and clients can subscribe to that information. Each time the server publishes more information, all subscribers receive it. Throughout the examples of this chapter, we will see that many of the networking details are handled by the Java APIs.