- Java Programming Basics
- Java Tutorial
- Java Overview
- Java Environment Setup
- Java Program Structure
- Java Basic Syntax
- Java First Program
- Java Constants
- Java Separators
- Java Keywords
- Java Data Types
- Java Data Types
- Java Integers
- Java Floating Point
- Java Characters
- Java Booleans
- Java Numbers
- Java Programming Variables
- Java Variables
- Java Variable Types
- Java Variable Scope
- Java Type Conversion
- Java Type Casting
- Java Auto Type Promotion
- Java Type Promotion Rules
- Java Programming Arrays
- Java Arrays
- Java One Dimensional Array
- Java Multidimensional Array
- Java Programming Operators
- Java Operators
- Java Arithmetic Operators
- Java Increment Decrement
- Java Bitwise Operators
- Java Left Shift
- Java Right Shift
- Java Relational Operators
- Java Boolean Logical Operators
- Java Ternary(?) Operator
- Java Operator Precedence
- Java Control Statements
- Java Decision Making
- Java if if-else if-else-if
- Java switch Statement
- Java Loops
- Java while Loop
- Java do-while Loop
- Java for Loop
- Java for-each Loop
- Java Nested Loops
- Java break Statement
- Java continue Statement
- Java Class Object Method
- Java Classes and Objects
- Java Class
- Java Object
- Java new Operator
- Java Methods
- Java Constructors
- Java this Keyword
- Java Stack
- Java Overloading Recursion
- Java Method Overloading
- Java Constructor Overloading
- Java Object as Parameter
- Java Call by Value Reference
- Java Returning Objects
- Java Recursion
- Java Modifier Types
- Java Encapsulate Poly String
- Java Encapsulation
- Java Polymorphism
- Java Nested Inner Class
- Java Strings
- Java Command Line Arguments
- Java Variable Length Arguments
- Java Inheritance Abstraction
- Java Inheritance
- Java super Superclass
- Java Multilevel Hierarchy
- Java Method Overriding
- Java Abstraction
- Java Packages Interfaces
- Java Packages
- Java Access Protection
- Java Import Statement
- Java Interfaces
- Java Programming Exceptions
- Java Exception Handling
- Java try catch
- Java throw throws
- Java finally Block
- Java Built In Exceptions
- Java Exception Subclasses
- Java Chained Exceptions
- Java Multithreading
- Java Multithreading
- Java Thread Model
- Java Main Thread
- Java Create Thread
- Java Thread Priorities
- Java Synchronization
- Java Inter Thread Communication
- Java Suspend Resume Stop Thread
- Java Get Thread State
- Java Enum Autobox Annotation
- Java Enumerations
- Java Type Wrappers
- Java Autoboxing
- Java Annotation
- Java Marker Annotations
- Java Single Member Annotation
- Java Built In Annotations
- Java Type Annotations
- Java Repeating Annotations
- Java Data File Handling
- Java Files I/O
- Java Streams
- Java Read Console Input
- Java Write Console Output
- Java PrintWriter Class
- Java Read Write Files
- Java Automatically Close File
- Java Programming Advance
- Java Date and Time
- Java Regular Expressions
- Java Collections Framework
- Java Generics
- Java Data Structures
- Java Network Programming
- Java Serialization
- Java Send Email
- Java Applet Basics
- Java Documentation
- Java Programming Examples
- Java Programming Examples
Java Create Thread
In most general cases, you create a thread by instantiating an object of the type Thread.
Java defines the following two ways in which this can be attained :
- You can implement the Runnable interface
- You can extend the Thread class, itself
Now let's discuss each method one by one.
Implement Runnable in Java
The easiest way to create a thread is to create a class that implements the Runnable interface.
The Runnable abstracts a unit of executable code. You can construct a thread on any object that implements the Runnable. To implement Runnable, a class require only implement a single method called run(), which is declared like this:
public void run()
Inside the run() method, you will define the code that constitutes the new thread. It is important to understand that the method run() can call the other methods, use other classes, and declare variables, just like the main thread can. The only difference is that the method run() establishes the entry point for another, concurrent thread of execution within your program. This thread will end when the method run() returns.
After you create a class that implements the Runnable, you will instantiate an object of Thread type from within that class. Thread defines several constructors. The one that we will use is shown here :
Thread(Runnable threadOb, String threadName)
In this constructor, threadOb is an instance of a class that implements the Runnable interface. And this defines, where the execution of the thread will start. The name of the new thread is specified by threadName.
After the new thread is created, will not start running until when you call its method start(), which is declared within Thread. In essence, the start() method executes a call to run() method. The start() method is shown below :
void start()
Java Create Thread Example
Below is an example that creates a new thread and starts it running :
/* Java Program Example - Java Creating a Thread * Implement Runnable interface * Create a second thread */ class NewThread implements Runnable { Thread thr; NewThread() { /* create a new, second thread */ thr = new Thread(this, "Demo Thread"); System.out.println("Child thread : " + thr); thr.start(); // start the thread } /* this is the entry point for second thread */ public void run() { try { for(int n=5; n>0; n--) { System.out.println("Child thread : " + n); Thread.sleep(500); } } catch(InterruptedException e) { System.out.println("Child interrupted"); } System.out.println("Exiting child thread..."); } } class JavaProgram { public static void main(String args[]) { new NewThread(); // create a new thread try { for(int n=5; n>0; n--) { System.out.println("Main Thread : " + n); Thread.sleep(1000); } } catch(InterruptedException e) { System.out.println("Main thraed interrupted"); } System.out.println("Main thread exiting"); } }
Within the NewThread's constructor, a new Thread object is created by this statement:
thr = new Thread(this, "Demo thread");
Passing this as the first argument which indicates that you want the new thread to call the method run() on this object. Next, start() is called, which starts the thread of execution starting at the method run(). This cause the child thread's for loop to begin. After calling the start() method, NewThread's constructor returns to the main() method. When the main thread resumes, it enters its for loop. And both the threads continue running, sharing the CPU in single-core systems, until their loops finish. The output produced by the this program is shown here:
As mentioned earlier, in a multithreaded program, often the main thread must be the final thread to finish running. In fact, for some older JVMs, if the main thread finishes before the child thread has completed, then the Java run-time system may "hang". The preceding program ensures that the main thread finishes last, as the main thread sleeps for 1,000 milliseconds between iterations, but the child thread sleeps for 500 milliseconds only. This causes the child thread to terminate earlier than the main thread. Soon, you will see a better way to wait for a thread to finish.
Extend Thread
The second style to create a thread is to create a new class that extends the Thread, and then to create an instance of the class. The extending class must override the run(), which is the entry point for the new thread. It must also call the method start() to start the execution of the new thread.
Example
Following is the preceding program rewritten to extend Thread :
/* Java Program Example - Java Creating a Thread * Extending 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 second thread */ public void run() { try { for(int n=5; n>0; n--) { System.out.println("Child thread : " + n); Thread.sleep(500); } } catch(InterruptedException e) { System.out.println("Child interrupted..!!"); } System.out.println("Exiting child thread..."); } } class JavaProgram { public static void main(String args[]) { new NewThread(); // create a new thread try { for(int n=5; n>0; n--) { System.out.println("Main Thread : " + n); Thread.sleep(1000); } } catch(InterruptedException e) { System.out.println("Main thraed interrupted..!!"); } System.out.println("Exiting main thread"); } }
The above Java program produce the same output as of above program, shown below :
As you can see, the child thread is created by instantiating an object of NewThread, which is derived from Thread.
Notice here, the call to the super() method within the NewThread. This invokes the following form of the Thread constructor:
public Thread(String threadName)
In this statement, the threadName specifies the name of the thread
« Previous Tutorial Next Tutorial »