- 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 Main Thread
Once a Java program starts, one thread starts running immediately. This is usually called main thread of your program, because it is the one which is executed when your program starts. The main thread is important for the following two reasons:
- It is the thread from which the other (child) threads will be spawned
- Often, it must be the last thread to finish the execution as it performs various shutdown actions
Although the main thread is automatically created when your program starts, it can be controlled through a Thread object. To do so, you must
obtain a reference to it by calling the method named currentThread(), is a public static member of the Thread. Its general form is :
static Thread currentThread()
This method returns a reference to the thread in which it is called. And once you have a reference to the main thread, you can control it just like any other thread.
Java Main Thread Example
Here is an example demonstrates the concept of main thread in Java:
/* Java Program Example - Java Main Thread * This program control the main Thread */ class JavaProgram { public static void main(String args[]) { Thread thr = Thread.currentThread(); System.out.println("Current thread : " + thr); /* change the name of the thread */ thr.setName("My Thread"); System.out.println("After name change : " + thr); try { for(int i=5; i>0; i--) { System.out.println(i); Thread.sleep(1000); } System.out.println("stopped"); } catch(InterruptedException e) { System.out.println("Main thread interrupted"); } } }
When the above Java program is compile and executed, it will produce the following output:
In the above program, a reference to the current thread (main thread in this case) is obtained by calling the currentThread() method, and this reference is stored in the local variable i.e., thr. Next, the program displays the information about the thread. The program then calls setName() method to change the internal name of the thread. Data about the thread is then redisplayed. Next, a loop counts down from five, pausing one second between each line. The pause is executed by the sleep() method. The argument to sleep() specifies the delay period in milliseconds.
Notice here that the try/catch block around this loop. The sleep() method in the Thread might throw an interruptedException. It will happen only if some other thread wanted to interrupt this sleeping one. This program just prints a message (as shown in above program) if it gets interrupted.
Notice that the output produced when thr is used as an argument to println(). This displays, in order, the name of the thread, and its priority, and then the name of its group.
By default, the name of the main thread is main.And its priority is 5, which is the default value, and main is also the name of the group of threads to which this thread belongs to.
A thread group is a data structure that controls the state of a collection of threads as a whole. After the name of the thread is altered, thr is again output. This time, the new name of the thread is displayed.
In the above program, as you can see, sleep() causes the thread from which it is called to suspend execution for the given period of milliseconds. Its general form is :
static void sleep(long milliseconds) throws InterruptedException
The number of milliseconds to suspend is given in milliseconds. This method may throw an InterruptedException.
The sleep() has a second form, shown next, allows you to specify the period in terms of milliseconds and nanoseconds:
static void sleep(long milliseconds, int nanoseconds) throws InterruptedException
This second form of sleep() method is useful only in environments that allow timing periods as short as nanoseconds.
As the preceding program shows, you can use setName() method to set the name of a thread.
You can obtain the name of the thread by calling the method getName() (this method is not shown in the above program, but you can try it). These methods are the members of the Thread class and are declared like this :
final void setName(String threadName) final String getName()
Here, threadName specifies the name of the thread.
« Previous Tutorial Next Tutorial »