Java
  Home arrow Java arrow Page 7 - Multithreading in Java
IBM Developerworks
FaxWave - Free Trial.
Dev Articles Forums 
ADO.NET  
Apache  
ASP  
ASP.NET  
C#  
C++  
ColdFusion  
COM/COM+  
Delphi-Kylix  
Design Usability  
Development Cycles  
DHTML  
Embedded Tools  
Flash  
Graphic Design  
HTML  
IIS  
Interviews  
Java  
JavaScript  
MySQL  
Oracle  
Photoshop  
PHP  
Reviews  
Ruby-on-Rails  
SQL  
SQL Server  
Style Sheets  
VB.Net  
Visual Basic  
Web Authoring  
Web Services  
Web Standards  
XML  
Dedicated Servers  
Download TestComplete 
IBM® developerWorks 
Weekly Newsletter
 
Developer Updates  
Free Website Content 
IBM Rational Software Development Conference
 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? 
JAVA

Multithreading in Java
By: McGraw-Hill/Osborne
  • Search For More Articles!
  • Disclaimer
  • Author Terms
  • Rating: 4 stars4 stars4 stars4 stars4 stars / 193
    2005-08-04

    Table of Contents:
  • Multithreading in Java
  • Overhead
  • The Thread Classes and the Runnable Interface
  • Creating Your Own Thread
  • Creating a Thread by Using extends
  • Using isAlive() and join()
  • Setting Thread Priorities
  • Synchronizing Threads
  • Using the Synchronized Statement
  • Suspending and Resuming Threads

  • Rate this Article: Poor Best 
      ADD THIS ARTICLE TO:
      Del.ici.ous Digg
      Blink Simpy
      Google Spurl
      Y! MyWeb 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
     
     
    Iron Speed
     
    ADVERTISEMENT

    Ajax Application Generator Generate database and reporting .NET Web apps in minutes. Quickly create visually stunning, feature-rich apps that are easy to customize and ready to deploy. Download Now!

    Multithreading in Java - Setting Thread Priorities
    (Page 7 of 10 )

    Previously in this chapter, you learned that each thread has an assigned priority that is used to let more important threads use resources ahead of lower-priority resources. Priority is used as a guide for the operating system to determine which thread gets accesses to a resource such as the CPU. In reality, an operating system takes other factors into consideration. Typically, programmers have little or no control over those other factors. Therefore, they establish a priority for their threads without further concern over those other factors.

    A priority is an integer from 1 to 10 inclusive, where 10 is the highest priority, referred to as the maximum priority, and 1 is the lowest priority, also known as the minimum priority. The normal priority is 5, which is the default priority for each thread.

    In general, a thread with a higher priority bumps a thread with a lower priority from using a resource. The lower-priority thread pauses until the higher-priority thread is finished using the resource. Whenever two threads of equal priority need the same resource, the thread that accesses the resource first has use of the resource. What happens to the second thread depends on the operating system under which your program is running. Some operating systems force the second thread to wait until the first thread is finished with the resource. Other operating systems require the first thread to give the second thread access to the resource after a specified time period. This is to ensure that one thread doesn’t hog a resource and prevent other threads from utilizing it.

    In the real world, the first thread usually pauses while using the resource because another resource it needs isn’t available. It is during this pause that the operating system has the first thread relinquish the resource. The problem is, you don’t know if and when the pause will occur. It is best to always cause a thread to pause periodically whenever the thread is using a resource for a long period time. In this way, the thread shares the resource with other threads. You learn how to pause a thread in the “Suspending and Resuming a Thread” section of this chapter.

    You need to keep in mind that there is a downside to periodically pausing a thread. Pausing a thread diminishes the performance of your program and could cause a backlog for use of the resource. Therefore, you need to monitor the performance of your program regularly to make sure you are not experiencing this negative aspect of pausing a thread.

    For now let’s focus on something you do have control over—setting the priority of a thread. You set a thread’s priority by calling the setPriority() method, which is defined in the Thread class. The setPriority() method requires one parameter, which is the integer representing the level of priority. You have two ways in which to represent the priority. You can use an integer from 1 to 10, or you can use final variables defined in the Thread class. These variables are MIN_PRIORITY, MAX_PRIOIRTY, and NORM_PRIOIRTY.

    You can determine the priority level of a thread by calling the getPriority() method, which is also defined in the Thread class. The getPriority() method does not requires an argument, and it returns the integer representing the level of priority for the thread.

    The following example illustrates how to use the setPriority() and getPriority() methods. This example creates two child threads and sets the priority for each. First, the low-priority thread starts, followed by the high-priority thread. Here’s what is displayed when you run this program (notice that the high-priority thread runs ahead of the low-priority thread, even though the low-priority thread started first):


    NOTE:   The results displayed on your screen might be different from the results shown here because of the way your operating system handles thread priorities.

    low priority started
    high priority started
    high priority running.
    low priority running.
    low priority stopped.
    high priority stopped.
    class MyThread implements Runnable {
      Thread t;
      private volatile boolean running = true;
      public MyThread (int p, String tName) {
        
    t = new Thread(this,tName);
        
    t.setPriority (p);
      }
      public void run() {
        
    System.out.println(t.getName() + " running.");
      }
      public void stop() {
        
    running = false;
        
    System.out.println(t.getName() + " stopped.");
      }
      public void start() {
        
    System.out.println(t.getName() + " started");
         t.start();
      }
    }
    class Demo {
     
    public static void main(String args[] ) {
         Thread.currentThread().setPriority(10);
         MyThread lowPriority =
                    
    new MyThread (3, "low priority");
         MyThread highPriority =
                    
    new MyThread (7, "high priority"); 
         lowPriority.start();
         highPriority.start();
         try {
           
    Thread.sleep(1000);
         } catch ( InterruptedException e) {
           
    System.out.println("Main thread interrupted.");
         }
         lowPriority.stop();
         highPriority.stop();
         try {
           
    highPriority.t.join();
            lowPriority.t.join();
         } catch (InterruptedException e) {
              System.out.println(
                      "InterruptedException caught");
         }
      }
    }

    More Java Articles
    More By McGraw-Hill/Osborne


       · Keep up the Good work sir.Thanks Kiran
       · This is the best introduction to multithreading i ever had......Thanks a...
       · Hello sir, this is the best online tutorial on multithreading, I have seen many but...
       · Hi,This is really a good tutorial on multithreading concept for begineers. It...
       · It is very easy to understand,with simple language.I.V.N.Venu
       · Example in chapter Five is not so Elucidate.I.V.N.Venu
       · Great job....Thanks alot ...Sanesh
       · sir i have read u r notes it's very easy to understand,very good sir
       · This is trully a very good article as it covers in one piece all the important...
       · Why does all the indian programmers say "sir"? Guys you r not in a school and the...
       · Good Job.It helps me a lot...Keep Going
       · The Hindi Language has an equivalent of "sir" that's used to address any stranger as...
       · This is the best platform from where I can learnmultithreading,thanks..Paresh
       · It is very easy to learn
       · it is very useful n connecting the sources indeed
       · Nice job..Good Article...Very nice..Rakesh..
       · The tutorial is nice, but in chapter 9, when I tried to run the program with wait()...
       · this is very good and easy to read and understand,but the whole data of threads...
       · I found good matter on multithreadig which help me a lot to understand...
       · Please check the sample example.After some analysis, I found the busy flag is...
       · Hi ,It is not much because of the language, its got more to do the with the...
     

    Buy this book now. This article is excerpted from chapter 10 of the book Java Demystified, written by Jim Keogh (McGraw-Hill/Osborne, 2004; ISBN: 0072254548). Check it out at your favorite bookstore today. Buy this book now.

    JAVA ARTICLES

    - 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 ...
    - Generics and Limitations in Java
    - Getting Started with Java Web Development in...

    Iron Speed

     
    Accelerating Trading Partner Performance
     
    Competing on Analytics
     
    Cost Effective Scaling with Virtualization and Coyote Point Systems
     
    Five Checkpoints to Implementing IP Telephony
     
    Hosted Email Security: Staying Ahead of New Threats
     





    © 2003-2008 by Developer Shed. All rights reserved. DS Cluster 1 hosted by Hostway