Let us start by looking at a program that does not use multiple threads and that, as a consequence, makes it difficult for the user to perform several tasks with that program. After we dissect it, we then show you how easy it is to have this program run separate threads. This program animates a bouncing ball by continually moving the ball, finding out if it bounces against a wall, and then redrawing it.
Using a thread to animate a bouncing ball
As soon as you click the Start button, the program launches a ball from the upper-leftcorner of the screen and the ball begins bouncing. The handler of the Start button calls the addBall method. That method contains a loop running through 1,000 moves. Each call to move moves the ball by a small amount, adjusts the direction if it bounces against a wall, and then redraws the panel.
The static sleep method of the Thread class pauses for the given number of milliseconds. The call to Thread.sleep does not create a new thread—sleep is a static method of the Threadclass that temporarily stops the activity of the current thread.
The sleep method can throw an InterruptedException. We discuss this exception and its proper handling later. For now, we simply terminate the bouncing if this exception occurs.
If you run the program, the ball bounces around nicely, but it completely takes over the application. If you become tired of the bouncing ball before it has finished its 1,000 moves and click the Close button, the ball continues bouncing anyway. You cannot interact withthe program until the ball has finished bouncing.
NOTE: If you carefully look over the code at the end of this section, you will notice the call
inside the addBall method of the BounceFrame class. That is pretty strange —normally, you’d call repaint and let the AWT worry about getting the graphics context and doing the painting. But if you try to call comp.repaint() in this program, you’ll find that the panel is never repainted
because the addBall method has completely taken over all processing. Also note that the ball component extends JPanel; this makes it easier to erase the back ground. In the next program, in which we use a separate thread to compute the ball position, we can go back to the familiar use of repaint and JComponent.
Obviously, the behavior of this program is rather poor. You would not want the programs that you use behaving in this way when you ask them to do a time -consuming job. After all, when you are reading data over a network connection, it is all too common to be stuck in a task that you would really like to interrupt. For example, suppose you download a large image and decide, after seeing a piece of it, that you do not need or want to see the rest; you certainly would like to be able to click a Stop or Back button to interrupt the loading process. In the next section, we show you how to keep the user in control by running crucial parts of the code in a separate thread.
Using Threads to Give Other Tasks a Chance
We will make our bouncing -ball program more responsive by running the code that moves the ball in a separate thread. In fact, you will be able to launch multiple balls. Each of them is moved by its own thread. In addition, the AWT event dispatch thread continues running in parallel, taking care of user interface events. Because each thread gets a chance to run, the event dispatch thread has the opportunity to notice when a user clicks the Close button while the balls are bouncing. The thread can then process the “close” action.
We use ball -bouncing code as an example to give you a visual impression of the need for concurrency. In general, you will always want to be wary of any long-running computation. Your computation is likely to be a part of some bigger framework, such as a GUI or web framework. Whenever the framework calls one of your methods, there is usually an expectation of a quick return. If you need to do any task that takes a long time, you should use a separate thread.
Here is a simple procedure for running a task in a separate thread:
To make our bouncing-ball program into a separate thread, we need only implement a class BallRunnable and place the code for the animation inside the run method, as in the following code:
Again, we need to catch an InterruptedException that the sleep method threatens to throw. We discuss this exception in the next section. Typically, interruption is used to request that a thread terminates. Accordingly, our run method exits when an InterruptedException occurs.
Whenever the Start button is clicked, the addBall method launches a new thread :
Running multiple threads
That’s all there is to it! You now know how to run tasks in parallel. The remainder of this section tells you how to control the interaction between threads.
NOTE: You can also define a thread by forming a subclass of the Thread class, like this:
Then you construct an object of the subclass and call its start method. However, this approach is no longer recommended. You should decouple the task that is to be run in parallel from the mechanism of running it. If you have many tasks, it is too expensive to create a separate thread for each one of them. Instead, you can use a thread pool.
CAUTION: Do not call the run method of the Thread class or the Runnable object. Calling the run method directly merely executes the task in the same thread —no new thread is started.
Instead, call the Thread.start method. It will create a new thread that executes the run method.
must be overriden and supplied with instructions for the task that you want to have executed.
Core Java Related Interview Questions
|J2EE Interview Questions||Core Java Interview Questions|
|JDBC Interview Questions||JSP Interview Questions|
|Android Interview Questions||JavaServer Faces (JSF) Interview Questions|
|Java collections framework Interview Questions||Java 8 Interview Questions|
|Java Collections Interview Questions||Java Exception Handling Interview Questions|
|Java Concurrency Interview Questions||Java Serialization Interview Questions|
|Java Programmer Interview Questions||Java Inheritance Interview Questions|
|Java IO Interview Questions||Object Oriented Programming in PHP Interview Questions|
Core Java Tutorial
An Introduction To Java
The Java Programming Environment
Fundamental Programming Structures In Java
Objects And Classes
Interfaces And Inner Classes
User Interface Components With Swing
Deploying Applications And Applets
Exceptions, Logging, Assertions, And Debugging
All rights reserved © 2018 Wisdom IT Services India Pvt. Ltd
Wisdomjobs.com is one of the best job search sites in India.