Nothing Special   »   [go: up one dir, main page]

01 Javathreads

Download as pdf or txt
Download as pdf or txt
You are on page 1of 7

JAVA THREADS

In Java, a process is an executing computer program that has a self-contained execution


environment, meaning that it has everything it needs to run, including memory space. A thread is
a lightweight process, having an execution environment that exists within that of a larger
process. A process has one or more threads, each of which shares the process’s resources,
including memory and open files. Two or more threads can run at the same time and, when they
do, are called concurrent threads.

Concurrent threads are implemented in one of two ways depending on the computer hardware
available. When multiple processors are available, concurrent threads can be executed in parallel,
each on its own processor. This is called physical concurrency.

Example
Suppose thread #1 computes a * b + c * d and thread #2 computes w * x + y * z. With two
processors the computation can proceed as follows:

Time Thread 1 (Processor 1) Thread 2 (Processor 2)


1 Compute A = a * b Compute A = w * x
2 Compute B = c * d Compute B = y * z
3 Compute A + B Compute A + B

When only one processor is available, it executes concurrent threads by interleaving the
execution of their individual operations, a process called logically concurrency.

Example
Suppose thread #1 computes a * b + c * d and thread #2 computes w * x + y * z. One processor
interleaves the machine operations. One possible interleaving is:

Time Processor
1 Compute A = a * b
2 Compute B = w * x
3 Compute C = c * d
4 Compute D = y * z
5 Compute A + C
6 Compute B + D

Java Threads Page 1


Interleaving is often done at the hardware level by timeslicing the concurrent threads. Each
thread is given an interval of time, called a quantum, to execute on the CPU. When its quantum
expires, the thread is suspended, put into a ready queue and the CPU is given a different thread to
execute for its quantum. Suspension and resumption of the threads continue in a round-robin
fashion so that all threads get a chance to advance their computation.

The behavior of concurrent threads is equivalent regardless of whether they are implemented
physically or logically. This means that the choice of physical or logical concurrency can be left
to the compiler and operating system without you having to make special allowances for it in
your code.

Java provides two mechanisms for creating your own threads. The first is to write a class that
extends the API class java.lang.Thread.

Thread Syntax #1
public class class name extends Thread
{
public class name ( String name )
{
super( name );
thread initialization code
}

public void run( )


{
thread execution code
}
}

Place into the constructor any initialization code you need and into method run whatever you
want your thread to do. The thread runs in the context of the Java program that creates it.

Java Threads Page 2


Example
The following class describes a concurrent thread object that increments a counter, displays it in
a JTextField and sleeps for some determined amount of time give by the value of the
variable delay. The run method, which is inherited from class
Thread and morphed appropriately, does this repeatedly. The class
constructor initializes the delay variable and builds a display panel
(shown at right) in which to show the value of the counter.

1 import javax.swing.*;
2 import java.awt.*;
3 import javax.swing.border.*;
4
5 public class Counter implements Runnable
6 {
7 private int counter = 0; // counter to increment
8 private int delay; // sleep time
9 private JTextField display; // display for counter
10 // fancy JPanel to display, made public so another
11 // object can add it to a containment hierarchy
12 public JPanel displayPanel;
13
14 public void run( )
15 // morphed from Thread to do what I want it to.
16 {
17 try // needed for call to Thread.sleep (see below)
18 {
19 while ( true ) // do forever
20 {
21 counter++; // increment counter & display
22 display.setText( Integer.toString( counter ) );
23 Thread.sleep( delay ); // sleep
24 // sleep can throw InterruptedException
25 }
26 }
27 catch( InterruptedException e )
28 { // probably won't happen, but we handle it anyway
29 String name = Thread.currentThread().getName();
30 System.out.println( name + " halted during run." );
31 return;

Java Threads Page 3


32 }
33 } // end run method
34
35 private final int DELAY_RANGE = 2000;
36
37 public Counter( String name )
38 {
39 // initialize this thread's delay to a random
40 // integer between 0.5 and 2.5 seconds
41 delay = (int)( Math.random( ) * DELAY_RANGE ) + 500;
42 // initialize the display JTextField
43 display = new JTextField( 4 );
44 display.setHorizontalAlignment( JTextField.RIGHT );
45 display.setEditable( false );
46 display.setFont(
47 new Font( "Courier New", Font.BOLD, 72 ) );
48 display.setBackground ( new Color( 255, 255, 153 ) );
49 display.setForeground ( new Color( 0, 0, 255 ) );
50 // create the fancy JPanel
51 displayPanel = new JPanel( );
52 displayPanel.setBorder(
53 new TitledBorder( new EtchedBorder( ), name ) );
54 // create box with delay label and value
55 Box delayBox = Box.createVerticalBox( );
56 delayBox.add( new JLabel( "Delay" ) );
57 delayBox.add( Box.createVerticalStrut( 5 ) );
58 delayBox.add(
59 new JLabel( Integer.toString( delay ) ) );
60 // add the JTextField and JLabel to the JPanel
61 displayPanel.add( display );
62 displayPanel.add( delayBox );
63 } // end constructor
64 }

Java Threads Page 4


To execute the thread, build a thread object from your class and use the inherited method start
to commence its run.

Example
The following Java applet builds a Counter object and starts it running.

1 import java.applet.*;
2 import java.awt.event.*;
3 import java.awt.*;
4
5 public class CounterThread extends Applet
6 {
7 public void init( )
8 {
9 // build the counter object
10 Counter counter = new Counter( "Counter 1" );
11 // change applet's layout (default is BorderLayout)
12 setLayout( new FlowLayout( ) );
13 // add counter's display panel to applet
14 add( counter.displayPanel );
15 // start thread running
16 counter.start( );
17 }
18 }

The second mechanism for creating your own threads is to write a class that implements the
interface java.lang.Runnable, which is also available in the Java API. Runnable
contains only one method, the unimplemented run, which you implement in the new class. The
Java API specification recommends using this technique if the run method is the only Thread
method you intend to morph.

Example
To write the Counter class using the Runnable interface, the code is exactly the same as
previously listed except for line 5, which must be changed to:

public class Counter implements Runnable

Java Threads Page 5


To execute a thread constructed from the Runnable interface:

1. Build the Runnable object.


2. Build a Thread from the Runnable object.
3. Call the thread’s start method.

Example
1 import java.applet.*;
2 import java.awt.event.*;
3 import java.awt.*;
4
5 public class CounterRunnable extends Applet
6 {
7 public void init( )
8 {
9 // build runnable object
10 Counter counter = new Counter( "Counter 1" );
11 // build the thread object from the runnable
12 Thread thread = new Thread( counter );
13 // change applet's layout (default is BorderLayout)
14 setLayout( new FlowLayout( ) );
15 // add counter's display panel to applet
16 add( counter.displayPanel );
17 // start thread running
18 thread.start( );
19 }
20 }

Java Threads Page 6


Exercises

1. Save the classes Counter and CounterThread to files. Compile and run them using
jGRASP.

2. Modify Counter class so that it implements Runnable. Save CounterRunnable to a


file. Compile and run the two classes using jGRASP.

3. Modify your program from exercise 1 so that


it builds and runs two counter threads.
Display them in a GUI similar to that shown
at right.

4. Repeat exercise 3 on your Counter class from exercise 2.

5. Modify your program from exercise 1 so that


it builds an array of 9 counter threads and
displays them in a 3 × 3 grid, as shown
below.

6. Repeat exercise 5 on your Counter class from exercise 2.

7. Modify your program from exercise 3 to add a


GO button to the GUI (see the picture to the
right). The two counter threads must not start
until the user clicks the GO button.

8. Repeat exercise 7 on your Counter class from exercise 2.

Java Threads Page 7

You might also like