Java
  Home arrow Java arrow Page 2 - The Basics of Multiple Threads in Java
Dev Shed Forums  
Administration  
AJAX  
Apache  
BrainDump  
DHTML  
Flash  
Java  
JavaScript  
Multimedia  
MySQL  
Oracle  
Perl  
PHP  
Practices  
Python  
Reviews  
Security  
Smartphone Development  
Style-Sheets  
Web Services  
XML  
Zend  
Zope  
Mobile Linux  
App Generation ROI  
IBM® developerWorks  
Forums Sitemap  
E-Commerce Hosting  
Linux Web Hosting  
Managed Hosting  
Small Business Hosting  
VPS Hosting  
Weekly Newsletter

 
Developer Updates  
Free Website Content 
 RSS  Articles
 RSS  Forums
 RSS  All Feeds
Write For Us Get Paid  
Request Media Kit
Contact Us  
Site Map  
Privacy Policy  
Support  
 USERNAME
 
 PASSWORD
 
 
  >>> SIGN UP!  
  Lost Password? 
Google.com  
JAVA

The Basics of Multiple Threads in Java
By: Barzan "Tony" Antal
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: starstarstarstarstar / 12
    2009-02-25


    Table of Contents:
  • The Basics of Multiple Threads in Java
  • The Basics and the Thread class
  • The Runnable Interface
  • Taking a Break!

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      error-file:tidyout.log Del.ici.ous error-file:tidyout.log Digg
      error-file:tidyout.log Blink error-file:tidyout.log Simpy
      error-file:tidyout.log Google error-file:tidyout.log Spurl
      error-file:tidyout.log Y! MyWeb error-file:tidyout.log Furl
    Email Me Similar Content When Posted
    Add Developer Shed Article Feed To Your Site
    Email Article To Friend
    Print Version Of Article
    PDF Version Of Article

     
     
    ADVERTISEMENT


    The Basics of Multiple Threads in Java - The Basics and the Thread class
    ( Page 2 of 4 )

     

    A traditional single-threaded application runs into a point where it "takes time" to accomplish a task, and then the entire program halts until that operation is completed, at which time the thread is able to move further. With multi-threading execution, if one thread "takes time," it won't block the flow of execution of other threads.  

    We should also note that if one of the threads modifies a thread-specific variable, then all of the threads will end up "noticing" and working with the new value. Threads are always in one of the following states: running, resumed, ready to run, suspended, or blocked

    The first is self-explanatory. The second is a kind of "ready to run" state after being suspended or blocked. A thread in the third state is obviously ready but has not started yet. The fourth state means the thread is temporarily suspended, while a thread in the final state is waiting for something.

    Each thread also has a given priority. These are numeric values ranging from 1 to 10. The default priority level is 5 (NORM_PRIORITY constant). A higher priority thread during execution has priority over a lower valued one. The highest priority level, 10, is referred to by the constant MAX_PRIORITY, while the lowest 1 is akin to MIN_PRIORITY. These values are final static int's (meaning "constants" in everyday coding language). 

    Under Java there are two possible ways to create threads. The first route involves doing a simple inheritance from the Thread class. The Thread class can be found inside the java.lang package. Extending this thread with a sub-class means inheriting the parent's attributes and methods. We are going to cover this a bit later, as well as the other solution, which is implementing the Runnable interface. Moreover, we'll explain the differences. 

    For now let's stick to the first route. What we're going to do once the inheritance is done is override the run() method within the sub-class. This is the place where we should actually write the part that tells it "what to do" once launched. Furthermore, we can create an object instance of the sub-class, and right after this we can call the start() method of the aforementioned object that kick-starts the thread. 

    class MyThread extends Thread{

    private int a;

     

    public MyThread(int a){

    this.a = a;

    }

    public void run(){

    for (int i = 1; i <= a; ++i){

    System.out.println(getName() + " is " + i);

    try{

    sleep(1000);

    }

    catch(InterruptedException e){}

    }

    }

    }

     

    class MainMyThread{

    public static void main(String args[]){

    MyThread thr1, thr2;

    thr1 = new MyThread(5);

    thr2 = new MyThread(10);

    thr1.start();

    thr2.start();

    }

    }

    The output of the above code snippet is the following. As you can see, the threads are being run simultaneously, so the lines are printed one after another at the same time until the count of five is reached. After that, only the second thread continues. The first thread dies since it has done its work. 

    Thread-0 is 1

    Thread-1 is 1

    Thread-0 is 2

    Thread-1 is 2

    Thread-0 is 3

    Thread-1 is 3

    Thread-0 is 4

    Thread-1 is 4

    Thread-0 is 5

    Thread-1 is 5

    Thread-1 is 6

    Thread-1 is 7

    Thread-1 is 8

    Thread-1 is 9

    Thread-1 is 10

    In the code snippet above we have explicitly called the start() method of the two threads. This is one way of doing it. However, some people prefer launching the start() method instantaneously as soon as the object instance is created (basically, a new thread is initialized). You can do this by calling the start() method from the constructor. 

    public MyThread(int a){

    this.a = a;

    start(); // this is the extra line, it starts the threads!

    }

    On the next page we're going to tackle the other solution for creating new threads. 



     
     
    >>> More Java Articles          >>> More By Barzan "Tony" Antal
     

       

    JAVA ARTICLES

    - Exception Handling Techniques in Java
    - More About Multithreading in Java
    - The Basics of Multiple Threads in Java
    - Data Access Using Spring Framework JDBC
    - New Object Initialization in Java
    - Adding Images With iTextSharp
    - Adding Columns With iTextSharp
    - Creating Simple PDF Files With iTextSharp
    - The Spring Framework: Understanding IoC
    - Introducing the Spring Framework
    - Java Classes
    - Completing the Syntactic Comparison of Java ...
    - Syntactic Comparison of Java and C/C++
    - Java Statements
    - Conditionals, Expressions and Other Java Ope...





    © 2003-2009 by Developer Shed. All rights reserved. DS Cluster 3 Hosted by Hostway
    For more Enterprise Application Development news, visit eWeek