You are on page 1of 8

Java - Multithreading Programming Tutorial

http://www.tutorialspoint.com/java/java_multithreading.htm

HOME

JAVA

PHP

Python

Ruby

Perl

HTML

CSS

Javascript

MySQL

C++

UNIX

MORE...

Advertisements

Previous Page
Java Basics
Java - Home Java - Overview Java - Environment Setup Java - Basic Syntax Java - Object & Classes Java - Basic Datatypes Java - Variable Types Java - Modifier Types Java - Basic Operators Java - Loop Control Java - Decision Making Java - Numbers Java - Characters Java - Strings Java - Arrays Java - Date & Time Java - Regular Expressions Java - Methods Java - Files and I/O Java - Exceptions

Next Page

Java provides built-in support for multithreaded programming. A multithreaded program contains two o more parts that can run concurrently. Each part of such a program is called a thread, and each threa defines a separate path of execution.

A multithreading is a specialized form of multitasking. Multitasking threads require less overhead tha multitasking processes.

I need to define another term related to threads: process: A process consists of the memory spac allocated by the operating system that can contain one or more threads. A thread cannot exist on its own it must be a part of a process. A process remains running until all of the non-daemon threads are don executing.

Multithreading enables you to write very efficient programs that make maximum use of the CPU, becaus idle time can be kept to a minimum.

A thread goes through various stages in its life cycle. For example, a thread is born, started, runs, an then dies. Following diagram shows complete life cycle of a thread.

Java Object Oriented


Java - Inheritance Java - Overriding Java - Polymorphism

1 of 8

2/4/2013 4:27 PM

Java - Multithreading Programming Tutorial

http://www.tutorialspoint.com/java/java_multithreading.htm

Java - Abstraction Java - Encapsulation Java - Interfaces Java - Packages Above mentioned stages are explained here:

New: A new thread begins its life cycle in the new state. It remains in this state until the program starts the thread. It is also referred to as a born thread. Runnable: After a newly born thread is started, the thread becomes runnable. A thread in this is considered to be executing its task.

Java Advanced
Java - Data Structures Java - Collections Java - Generics Java - Serialization Java - Networking Java - Sending Email

Waiting: Sometimes a thread transitions to the waiting state while the thread waits for anoth thread to perform a task.A thread transitions back to the runnable state only when another threa signals the waiting thread to continue executing.

Timed waiting: A runnable thread can enter the timed waiting state for a specified interval of time A thread in this state transitions back to the runnable state when that time interval expires or whe the event it is waiting for occurs.

Terminated: A runnable thread enters the terminated state when it completes its task or otherwis terminates.

Java - Multithreading
Java - Applet Basics Java - Documentation

Every Java thread has a priority that helps the operating system determine the order in which threads ar scheduled. Java priorities are in the range between MIN_PRIORITY (a constant of 1) and MAX_PRIOR constant of 10). By default, every thread is given priority NORM_PRIORITY (a constant of 5).

Java Useful Resources


Java - Quick Guide Java - Library Classes Java Useful Resources Java - Examples

Threads with higher priority are more important to a program and should be allocated processor tim before lower-priority threads. However, thread priorities cannot guarantee the order in which thread execute and very much platform dependentant.

Java defines two ways in which this can be accomplished:

Selected Reading
Developer's Best Practices Computer Glossary Who is Who

You can implement the Runnable interface. You can extend the Thread class, itself.

The easiest way to create a thread is to create a class that implements the Runnable interface.

To implement Runnable, a class need only implement a single method called run( ), which is declared lik this: public void run( )

You will define the code that constitutes the new thread inside run() method. It is important to understan that run() can call other methods, use other classes, and declare variables, just like the main thread can.

After you create a class that implements Runnable, you will instantiate an object of type Thread from within that class. Thread defines several constructors. The one that we will use is shown here: Thread(Runnable threadOb, String threadName); Here threadOb is an instance of a class that implements the Runnable interface and the name of the thread is specified by threadName.

After the new thread is created, it will not start running until you call its start( ) method, which is declare within Thread. The start( ) method is shown here: void start( );

2 of 8

2/4/2013 4:27 PM

Java - Multithreading Programming Tutorial

http://www.tutorialspoint.com/java/java_multithreading.htm

Here is an example that creates a new thread and starts it running: // Create a new thread. class NewThread implements Runnable { Thread t; NewThread() { // Create a new, second thread t = new Thread(this, "Demo Thread"); System.out.println("Child thread: " + t); t.start(); // Start the thread } // This is the entry point for the second thread. public void run() { try { for(int i = 5; i > 0; i--) { System.out.println("Child Thread: " + i); // Let the thread sleep for a while. Thread.sleep(500); } } catch (InterruptedException e) { System.out.println("Child interrupted."); } System.out.println("Exiting child thread."); } } public class ThreadDemo { public static void main(String args[]) { new NewThread(); // create a new thread try { for(int i = 5; i > 0; i--) { System.out.println("Main Thread: " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Main thread interrupted."); } System.out.println("Main thread exiting."); } } This would produce following result: Child thread: Thread[Demo Thread,5,main] Main Thread: 5 Child Thread: 5 Child Thread: 4 Main Thread: 4 Child Thread: 3 Child Thread: 2 Main Thread: 3 Child Thread: 1 Exiting child thread. Main Thread: 2 Main Thread: 1 Main thread exiting.

The second way to create a thread is to create a new class that extends Thread, and then to create an instance of that class. The extending class must override the run( ) method, which is the entry point for the new thread. It must

3 of 8

2/4/2013 4:27 PM

Java - Multithreading Programming Tutorial

http://www.tutorialspoint.com/java/java_multithreading.htm

also call start( ) to begin execution of the new thread.

Here is the preceding program rewritten to extend Thread: // Create a second thread by extending Thread class NewThread extends Thread { NewThread() { // Create a new, second thread super("Demo Thread"); System.out.println("Child thread: " + this); start(); // Start the thread } // This is the entry point for the second thread. public void run() { try { for(int i = 5; i > 0; i--) { System.out.println("Child Thread: " + i); // Let the thread sleep for a while. Thread.sleep(500); } } catch (InterruptedException e) { System.out.println("Child interrupted."); } System.out.println("Exiting child thread."); } } public class ExtendThread { public static void main(String args[]) { new NewThread(); // create a new thread try { for(int i = 5; i > 0; i--) { System.out.println("Main Thread: " + i); Thread.sleep(1000); } } catch (InterruptedException e) { System.out.println("Main thread interrupted."); } System.out.println("Main thread exiting."); } } This would produce following result: Child thread: Thread[Demo Thread,5,main] Main Thread: 5 Child Thread: 5 Child Thread: 4 Main Thread: 4 Child Thread: 3 Child Thread: 2 Main Thread: 3 Child Thread: 1 Exiting child thread. Main Thread: 2 Main Thread: 1 Main thread exiting.

Following is the list of important medthods available in the Thread class. SN Methods with Description

4 of 8

2/4/2013 4:27 PM

Java - Multithreading Programming Tutorial

http://www.tutorialspoint.com/java/java_multithreading.htm

public void start() Starts the thread in a separate path of execution, then invokes the run() method on this Thread object. public void run() If this Thread object was instantiated using a separate Runnable target, the run() method is invoked on that Runnable object. public final void setName(String name) Changes the name of the Thread object. There is also a getName() method for retrieving the name. public final void setPriority(int priority) Sets the priority of this Thread object. The possible values are between 1 and 10. public final void setDaemon(boolean on) A parameter of true denotes this Thread as a daemon thread. public final void join(long millisec) The current thread invokes this method on a second thread, causing the current thread to block until the second thread terminates or the specified number of milliseconds passes. public void interrupt() Interrupts this thread, causing it to continue execution if it was blocked for any reason. public final boolean isAlive() Returns true if the thread is alive, which is any time after the thread has been started but before it runs to completion.

4 5

The previous methods are invoked on a particular Thread object. The following methods in the Thread class are static. Invoking one of the static methods performs the operation on the currently running thread SN Methods with Description 1 public static void yield() Causes the currently running thread to yield to any other threads of the same priority that are waiting to be scheduled public static void sleep(long millisec) Causes the currently running thread to block for at least the specified number of milliseconds public static boolean holdsLock(Object x) Returns true if the current thread holds the lock on the given Object. public static Thread currentThread() Returns a reference to the currently running thread, which is the thread that invokes this method. public static void dumpStack() Prints the stack trace for the currently running thread, which is useful when debugging a multithreaded application.

2 3 4

The following ThreadClassDemo program demonstrates some of these methods of the Thread class: // File Name : DisplayMessage.java // Create a thread to implement Runnable public class DisplayMessage implements Runnable { private String message; public DisplayMessage(String message) { this.message = message; } public void run() { while(true)

5 of 8

2/4/2013 4:27 PM

Java - Multithreading Programming Tutorial

http://www.tutorialspoint.com/java/java_multithreading.htm

{ System.out.println(message); } } } // File Name : GuessANumber.java // Create a thread to extentd Thread public class GuessANumber extends Thread { private int number; public GuessANumber(int number) { this.number = number; } public void run() { int counter = 0; int guess = 0; do { guess = (int) (Math.random() * 100 + 1); System.out.println(this.getName() + " guesses " + guess); counter++; }while(guess != number); System.out.println("** Correct! " + this.getName() + " in " + counter + " guesses.**"); } } // File Name : ThreadClassDemo.java public class ThreadClassDemo { public static void main(String [] args) { Runnable hello = new DisplayMessage("Hello"); Thread thread1 = new Thread(hello); thread1.setDaemon(true); thread1.setName("hello"); System.out.println("Starting hello thread..."); thread1.start(); Runnable bye = new DisplayMessage("Goodbye"); Thread thread2 = new Thread(hello); thread2.setPriority(Thread.MIN_PRIORITY); thread2.setDaemon(true); System.out.println("Starting goodbye thread..."); thread2.start(); System.out.println("Starting thread3..."); Thread thread3 = new GuessANumber(27); thread3.start(); try { thread3.join(); }catch(InterruptedException e) { System.out.println("Thread interrupted."); } System.out.println("Starting thread4..."); Thread thread4 = new GuessANumber(75); thread4.start(); System.out.println("main() is ending..."); } } This would produce following result. You can try this example again and again and you would get different result every time.

6 of 8

2/4/2013 4:27 PM

Java - Multithreading Programming Tutorial

http://www.tutorialspoint.com/java/java_multithreading.htm

Starting hello thread... Starting goodbye thread... Hello Hello Hello Hello Hello Hello Hello Hello Hello Thread-2 guesses 27 Hello ** Correct! Thread-2 in 102 guesses.** Hello Starting thread4... Hello Hello ..........remaining result produced.

While doing Multithreading programming, you would need to have following concepts very handy: Thread Synchronization Interthread Communication Thread Deadlock Thread Control: Suspend, Stop and Resume

The key to utilizing multithreading support effectively is to think concurrently rather than serially. For example, when you have two subsystems within a program that can execute concurrently, make them individual threads. With the careful use of multithreading, you can create very efficient programs. A word of caution is in order, however: If you create too many threads, you can actually degrade the performance of your program rather than enhance it. Remember, some overhead is associated with context switching. If you create too many threads, more CPU time will be spent changing contexts than executing your program!

Previous Page
Advertisements

Print Version

PDF Version

Next Page

7 of 8

2/4/2013 4:27 PM

Java - Multithreading Programming Tutorial

http://www.tutorialspoint.com/java/java_multithreading.htm

Laser Marking Printers


videojet.com/Free_Whitepaper Laser Marking On Any Surface w/ A Wide Range Of Application Option!

ASP.NET | jQuery | AJAX | ANT | JSP | Servlets | log4j | iBATIS | Hibernate | JDBC | Struts | HTML5 |

Copyright 2013 by tutorialspoint. All Rights Reserved.

8 of 8

2/4/2013 4:27 PM

You might also like