Home arrow Java arrow Page 5 - Multithreading in Java
JAVA

Multithreading in Java


Multithreading allows two parts of the same program to run concurrently. This article discusses how to pull off this performance-improving feat in Java. It is excerpted from chapter 10 of the book Java Demystified, written by Jim Keogh (McGraw-Hill/Osborne, 2004; ISBN: 0072254548).

Author Info:
By: McGraw-Hill/Osborne
Rating: 4 stars4 stars4 stars4 stars4 stars / 535
August 04, 2005
TABLE OF CONTENTS:
  1. · Multithreading in Java
  2. · Overhead
  3. · The Thread Classes and the Runnable Interface
  4. · Creating Your Own Thread
  5. · Creating a Thread by Using extends
  6. · Using isAlive() and join()
  7. · Setting Thread Priorities
  8. · Synchronizing Threads
  9. · Using the Synchronized Statement
  10. · Suspending and Resuming Threads

print this article
SEARCH DEVARTICLES

Multithreading in Java - Creating a Thread by Using extends
(Page 5 of 10 )

You can inherit the Thread class as another way to create a thread in your program. As youíll recall from Chapter 8, you can cause your class to inherit another class by using the keyword extends when defining your class. When you declare an instance of your class, youíll also have access to members of the Thread class.

Whenever your class inherits the Thread class, you must override the run() method, which is an entry into the new thread. The following example shows how to inherit the Thread class and how to override the run() method.

This example defines the MyThread class, which inherits the Thread class. The constructor of the MyThread class calls the constructor of the Thread class by using the super keyword and passes it the name of the new thread, which is My thread. It then calls the start() method to activate the new thread.

The start() method calls the run() method of the MyThread class. As youíll notice in this example, the run() method is overridden by displaying two lines on the screen that indicate that the child thread started and terminated. Remember that statements within the run()method constitute the portion of the program that runs as the thread. Therefore, your program will likely have more meaningful statements within the definition of the run() method than those used in this example.

The new thread is declared within the main() method of the Demo class, which is the program class of the application. After the thread starts, two messages are displayed, indicating the status of the main thread.

class MyThread extends Thread {
  
MyThread(){
    
super("My thread");
    
start();
  
}
  
public void run() {
      System.out.println("Child thread started");
      System.out.println("Child thread terminated");
  
}
}
class Demo {
  
public static void main (String args[]){
      new MyThread();
      System.out.println("Main thread started");
      System.out.println("Main thread terminated");
  
}
}


NOTE:   As a rule of thumb, you should implement the Runnable interface if the run() method is the only method of the Thread class that you need to override. You should inherit the Thread class if you need to override other methods defined in the Thread class.

Using Multiple Threads in a Program

It is not unusual to need to run multiple instances of a thread, such as when your program prints multiple documents concurrently. Programmers call this spawning a thread. You can spawn any number of threads you need by first defining your own class that either implements the Runnable interface or inherits the Thread class and then declaring instances of the class. Each instance is a new thread.

Letís see how this is done. The next example defines a class called MyThread that implements the Runnableinterface. The constructor of the MyThreadclass accepts one parameter, which is a string that is used as the name of the new thread. We create the new thread within the constructor by calling the constructor of the Thread class and passing it a reference to the object that is defining the thread and the name of the thread. Remember that the this keyword is a reference to the current object. The start() method is then called, which calls the run() method.

The run() method is overridden in the MyThread class. Two things happen when the run() method executes. First, the name of the thread is displayed on the screen. Second, the thread pauses for 2 seconds when the sleep() method is called. The sleep() method is defined in the Thread class can accept one or two parameters. The first parameter is the number of milliseconds the thread is to pause. The second parameter is the number of microseconds the thread pauses. In this example, weíre only interested in milliseconds, so we donít need to include the second parameter (2,000 nanoseconds is 2 seconds). After the thread pauses, another statement is displayed on the screen stating that the thread is terminating.

The main() method of the Demo class declares four instances of the same thread by calling the constructor of the MyThread class and passing it the name of the thread. Each of these is treated as a separate thread. The main thread is then paused 10 seconds by a call to the sleep() method. During this time, the threads continue to execute. When the main thread awakens, it displays the message that the main thread is terminating.

Hereís what is displayed on the screen when this example runs:

Thread: 1
Thread: 2
Thread: 3
Thread: 4
Terminating thread: 1
Terminating thread: 2
Terminating thread: 3
Terminating thread: 4
Terminating thread: main thread.
class MyThread implements Runnable {
  String tName;
  Thread t;
  MyThread (String threadName) {
    
tName = threadName;
     t = new Thread (this, tName);
     t.start();
 
}
  public void run() {
    
try {
        System.out.println("Thread: " + tName );
        Thread.sleep(2000);
    
} catch (InterruptedException e ) {
       System.out.println("Exception: Thread "
              
+ tName + " interrupted");
     }
     System.out.println("Terminating thread: " + tName );
 
}
}
class Demo {
   
public static void main (String args []) {
      new MyThread ("1");
      new MyThread ("2");
      new MyThread ("3");
      new MyThread ("4");
      try {
        
Thread.sleep (10000);
      } catch (InterruptedException e) {
        System.out.println(
                
"Exception: Thread main interrupted.");
      }
      System.out.println(
                 
"Terminating thread: main thread.");
  }
}


blog comments powered by Disqus
JAVA ARTICLES

- Java Too Insecure, Says Microsoft Researcher
- Google Beats Oracle in Java Ruling
- Deploying Multiple Java Applets as One
- Deploying Java Applets
- Understanding Deployment Frameworks
- Database Programming in Java Using JDBC
- Extension Interfaces and SAX
- Entities, Handlers and SAX
- Advanced SAX
- Conversions and Java Print Streams
- Formatters and Java Print Streams
- Java Print Streams
- Wildcards, Arrays, and Generics in Java
- Wildcards and Generic Methods in Java
- Finishing the Project: Java Web Development ...

Watch our Tech Videos 
Dev Articles Forums 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
Contact Us 
Site Map 
Privacy Policy 
Support 

Developer Shed Affiliates

 




© 2003-2017 by Developer Shed. All rights reserved. DS Cluster - Follow our Sitemap
Popular Web Development Topics
All Web Development Tutorials