0% found this document useful (0 votes)
127 views

Threads: Life Cycle of A Thread

Java allows multithreaded programming where multiple parts of a program can run concurrently using multiple CPUs. Threads share common resources like the CPU and allow subdivision of operations within an application into individual threads that can run in parallel. Threads go through various lifecycle stages from new to runnable to waiting, timed waiting, and terminated. Thread priorities determine scheduling order, with higher priority threads scheduled before lower priority ones. There are two main ways to create threads in Java: implementing the Runnable interface or extending the Thread class.

Uploaded by

Praneeth Mutnuru
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
127 views

Threads: Life Cycle of A Thread

Java allows multithreaded programming where multiple parts of a program can run concurrently using multiple CPUs. Threads share common resources like the CPU and allow subdivision of operations within an application into individual threads that can run in parallel. Threads go through various lifecycle stages from new to runnable to waiting, timed waiting, and terminated. Thread priorities determine scheduling order, with higher priority threads scheduled before lower priority ones. There are two main ways to create threads in Java: implementing the Runnable interface or extending the Thread class.

Uploaded by

Praneeth Mutnuru
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 18

Threads

Java is a multithreaded programming language which means we can develop


multithreaded program using Java. A multithreaded program contains two or more
parts that can run concurrently and each part can handle different task at the same
time making optimal use of the available resources specially when your computer
has multiple CPUs.
By definition multitasking is when multiple processes share common processing
resources such as a CPU. Multithreading extends the idea of multitasking into
applications where you can subdivide specific operations within a single
application into individual threads. Each of the threads can run in parallel. The OS
divides processing time not only among different applications, but also among
each thread within an application.
Multithreading enables you to write in a way where multiple activities can proceed
concurrently in the same program.
Life Cycle of a Thread:
A thread goes through various stages in its life cycle. For example, a thread is
born, started, runs, and then dies. Following diagram shows complete life cycle of
a thread.

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 state is considered to be executing its task.
Waiting: Sometimes, a thread transitions to the waiting state while the thread
waits for another thread to perform a task. A thread transitions back to the runnable
state only when another thread 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 transition back to the runnable state when
that time interval expires or when the event it is waiting for occurs.
Terminated: A runnable thread enters the terminated state when it completes its
task or otherwise terminates.

Thread Priorities:
Every Java thread has a priority that helps the operating system determine the order
in which threads are scheduled.
Java thread priorities are in the range between MIN_PRIORITY (a constant of 1)
and MAX_PRIORITY (a constant of 10). By default, every thread is given priority
NORM_PRIORITY (a constant of 5).
Threads with higher priority are more important to a program and should be
allocated processor time before lower-priority threads. However, thread priorities
cannot guarantee the order in which threads execute and very much platform
dependent.
Create Thread by Implementing Runnable Interface:
If your class is intended to be executed as a thread then you can achieve this by
implementing Runnable interface. You will need to follow three basic steps:
Step 1:
As a first step you need to implement a run() method provided by Runnable
interface. This method provides entry point for the thread and you will put you
complete business logic inside this method. Following is simple syntax of run()
method:
public void run( )
Step 2:
At second step you will instantiate a Thread object using the following
constructor:
Thread(Runnable threadObj, String threadName);
Where, threadObj is an instance of a class that implements the Runnable interface
and threadName is the name given to the new thread.
Step 3
Once Thread object is created, you can start it by calling start( ) method, which
executes a call to run( ) method. Following is simple syntax of start() method:
void start( );
Example:
Here is an example that creates a new thread and starts it running:
classRunnableDemo implements Runnable {
private Thread t;
private String threadName;
RunnableDemo( String name){
threadName = name;
System.out.println("Creating " + threadName );
}
public void run() {
System.out.println("Running " + threadName );
try {
for(inti = 4; i> 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}
public void start ()
{
System.out.println("Starting " + threadName );
if (t == null)
{
t = new Thread (this, threadName);
t.start ();
}
}
}
public class TestThread {
public static void main(String args[]) {
RunnableDemo R1 = new RunnableDemo( "Thread-1");
R1.start();
RunnableDemo R2 = new RunnableDemo( "Thread-2");
R2.start();
}
}
Create Thread by Extending Thread Class:
The second way to create a thread is to create a new class that extends Thread
class using the following two simple steps. This approach provides more flexibility
in handling multiple threads created using available methods in Thread class.
Step 1
You will need to override run( ) method available in Thread class. This method
provides entry point for the thread and you will put you complete business logic
inside this method. Following is simple syntax of run() method:
public void run( )
Step 2
Once Thread object is created, you can start it by calling start( ) method,
which executes a call to run( ) method. Following is simple syntax of
start() method:
void start( );
Example:
Here is the preceding program rewritten to extend Thread:
classThreadDemo extends Thread {
private Thread t;
private String threadName;
ThreadDemo( String name){
threadName = name;
System.out.println("Creating " + threadName );
}
public void run() {
System.out.println("Running " + threadName );
try {
for(inti = 4; i> 0; i--) {
System.out.println("Thread: " + threadName + ", " + i);
// Let the thread sleep for a while.
Thread.sleep(50);
}
} catch (InterruptedException e) {
System.out.println("Thread " + threadName + " interrupted.");
}
System.out.println("Thread " + threadName + " exiting.");
}
public void start ()
{
System.out.println("Starting " + threadName );
if (t == null)
{
t = new Thread (this, threadName);
t.start ();
}
}
}
public class TestThread {
public static void main(String args[]) {
ThreadDemo T1 = new ThreadDemo( "Thread-1");
T1.start();
ThreadDemo T2 = new ThreadDemo( "Thread-2");
T2.start();
}
}

Thread Methods:
Following is the list of important methods available in the Thread class.
Methods with Description
public void start()
1 Starts the thread in a separate path of execution, then invokes the run() method on
this Thread object.
public void run()
2 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)
3 Changes the name of the Thread object. There is also a getName() method for
retrieving the name.
public final void setPriority(int priority)
4
Sets the priority of this Thread object. The possible values are between 1 and 10.
public final void setDaemon(boolean on)
5
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
6
thread to block until the second thread terminates or the specified number of
milliseconds passes.
public void interrupt()
7 Interrupts this thread, causing it to continue execution if it was blocked for any
reason.
public final booleanisAlive()
8 Returns true if the thread is alive, which is any time after the thread has been
started but before it runs to completion.
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.
Methods with Description
public static void yield()
1 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)
2 Causes the currently running thread to block for at least the specified number of
milliseconds.
public static booleanholdsLock(Object x)
3
Returns true if the current thread holds the lock on the given Object.
public static Thread currentThread()
4 Returns a reference to the currently running thread, which is the thread that
invokes this method.
public static void dumpStack()
5 Prints the stack trace for the currently running thread, which is useful when
debugging a multithreaded application.
Example:
The following ThreadClassDemo program demonstrates some of these methods of
the Thread class. Consider a class DisplayMessage which implements Runnable:
// File Name : DisplayMessage.java
// Create a thread to implement Runnable
publicclassDisplayMessageimplementsRunnable
{
privateString message;
publicDisplayMessage(String message)
{
this.message= message;
}
publicvoid run()
{
while(true)
{
System.out.println(message);
}
}
}
Following is another class which extends Thread class:
// File Name : GuessANumber.java
// Create a thread to extentd Thread
publicclassGuessANumberextendsThread
{
privateint number;
publicGuessANumber(int number)
{
this.number= number;
}
publicvoid 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.**");
}
}
Following is the main program which makes use of above defined classes:
// File Name : ThreadClassDemo.java
publicclassThreadClassDemo
{
publicstaticvoid main(String[]args)
{
Runnable hello =newDisplayMessage("Hello");
Thread thread1 =newThread(hello);
thread1.setDaemon(true);
thread1.setName("hello");
System.out.println("Starting hello thread...");
thread1.start();
Runnable bye =newDisplayMessage("Goodbye");
Thread thread2 =newThread(bye);
thread2.setPriority(Thread.MIN_PRIORITY);
thread2.setDaemon(true);
System.out.println("Starting goodbye thread...");
thread2.start();
System.out.println("Starting thread3...");
Thread thread3 =newGuessANumber(27);
thread3.start();
try
{
thread3.join();
}catch(InterruptedException e)
{
System.out.println("Thread interrupted.");
}
System.out.println("Starting thread4...");
Thread thread4 =newGuessANumber(75);
thread4.start();
System.out.println("main() is ending...");
}
}

Thread Scheduler in Java


Thread scheduler in java is the part of the JVM that decides which thread should
run.
There is no guarantee that which runnable thread will be chosen to run by the
thread scheduler.
Only one thread at a time can run in a single process.
The thread scheduler mainly uses preemptive or time slicing scheduling to
schedule the threads.

Difference between preemptive scheduling and time slicing


Under preemptive scheduling, the highest priority task executes until it enters the
waiting or dead states or a higher priority task comes into existence. Under time
slicing, a task executes for a predefined slice of time and then reenters the pool of
ready tasks. The scheduler then determines which task should execute next, based
on priority and other factors.
Sleep method in java
The java sleep() method of Thread class is used to sleep a thread for the specified
milliseconds of time.

Syntax of sleep() method in java


The Thread class provides two methods for sleeping a thread:
public static void sleep(long miliseconds)throws InterruptedException
public static void sleep(long miliseconds, intnanos)throws InterruptedException

Example sleep method in java


class TestSleepMethod1 extends Thread{  
public void run(){  
for(int i=1;i<5;i++){  
try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}  
System.out.println(i);  
}  
}  
public static void main(String args[]){  
TestSleepMethod1 t1=new TestSleepMethod1();  
TestSleepMethod1 t2=new TestSleepMethod1();  
t1.start();  
t2.start();  
}  
}  
As you know well that at a time only one thread is executed. If you sleep a thread
for the specified time. The thread schedular picks up another thread and so on.

Synchronization in Java:
Synchronization in java is the capability of control the access of multiple threads to
any shared resource.
Java Synchronization is better option where we want to allow only one thread to
access the shared resource.
Uses of Synchronization:
The synchronization is mainly used to
 To prevent thread interference.
 To prevent consistency problem.

Types of Synchronization
There are two types of synchronization
 Process Synchronization
 Thread Synchronization
Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread
communication.
 Mutual Exclusive
 Synchronized method.
 Synchronized block.
 static synchronization.
 Cooperation (Inter-thread communication in java)

Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while
sharing data. This can be done by three ways in java:
by synchronized method
by synchronized block
by static synchronization

Understanding the concept of Lock in Java


Synchronization is built around an internal entity known as the lock or monitor.
Every object has an lock associated with it. By convention, a thread that needs
consistent access to an object's fields has to acquire the object's lock before
accessing them, and then release the lock when it's done with them.
From Java 5 the package java.util.concurrent.locks contains several lock
implementations.
Understanding the problem without Synchronization
In this example, there is no synchronization, so output is inconsistent. Let's see the
example:
Class Table{  
void printTable(int n){//method not synchronized  
for(int i=1;i<=5;i++){  
System.out.println(n*i);  
try{  
Thread.sleep(400);  
}catch(Exception e){System.out.println(e);}  
}  
}  
}  
class MyThread1 extends Thread{  
Table t;  
MyThread1(Table t){  
this.t=t;  
}  
public void run(){  
t.printTable(5);  
}  
  
}  
class MyThread2 extends Thread{  
Table t;  
MyThread2(Table t){  
this.t=t;  
}  
public void run(){  
t.printTable(100);  
}  
}  
  
class TestSynchronization1{  
public static void main(String args[]){  
Table obj = new Table();//only one object  
MyThread1 t1=new MyThread1(obj);  
MyThread2 t2=new MyThread2(obj);  
t1.start();  
t2.start();  
}  
}  

Java synchronized method


If you declare any method as synchronized, it is known as synchronized method.
Synchronized method is used to lock an object for any shared resource.
When a thread invokes a synchronized method, it automatically acquires the lock
for that object and releases it when the thread completes its task.
//example of java synchronized method  
class Table{  
synchronized void printTable(int n){//synchronized method  
for(int i=1;i<=5;i++){  
System.out.println(n*i);  
try{  
Thread.sleep(400);  
}catch(Exception e){System.out.println(e);}  
}  
}  
}  
 class MyThread1 extends Thread{  
Table t;  
MyThread1(Table t){  
this.t=t;  
}  
public void run(){  
t.printTable(5);  
}  
}  
class MyThread2 extends Thread{  
Table t;  
MyThread2(Table t){  
this.t=t;  
}  
public void run(){  
t.printTable(100);  
}  
}  
public class TestSynchronization2{  
public static void main(String args[]){  
Table obj = new Table();//only one object  
MyThread1 t1=new MyThread1(obj);  
MyThread2 t2=new MyThread2(obj);  
t1.start();  
t2.start();  
}  
}  

Synchronized block in java


Synchronized block can be used to perform synchronization on any specific
resource of the method.
Suppose you have 50 lines of code in your method, but you want to synchronize
only 5 lines, you can use synchronized block.
If you put all the codes of the method in the synchronized block, it will work same
as the synchronized method.
Points to remember for Synchronized block
Synchronized block is used to lock an object for any shared resource.
Scope of synchronized block is smaller than the method.
Syntax to use synchronized block
synchronized (object reference expression) {   
  //code block   
}  
Example of synchronized block
Let's see the simple example of synchronized block.
Program of synchronized block
class Table{  
void printTable(int n){  
synchronized(this){//synchronized block  
for(int i=1;i<=5;i++){  
System.out.println(n*i);  
try{  
Thread.sleep(400);  
}catch(Exception e){System.out.println(e);}  
}  
}  
}//end of the method  
}  
class MyThread1 extends Thread{  
Table t;  
MyThread1(Table t){  
this.t=t;  
}  
public void run(){  
t.printTable(5);  
}  
}  
class MyThread2 extends Thread{  
Table t;  
MyThread2(Table t){  
this.t=t;  
}  
public void run(){  
t.printTable(100);  
}  
}  
 public class TestSynchronizedBlock1{  
public static void main(String args[]){  
Table obj = new Table();//only one object  
MyThread1 t1=new MyThread1(obj);  
MyThread2 t2=new MyThread2(obj);  
t1.start();  
t2.start();  
}  
}  
Deadlock in java
Deadlock in java is a part of multithreading. Deadlock can occur in a situation
when a thread is waiting for an object lock, that is acquired by another thread and
second thread is waiting for an object lock that is acquired by first thread. Since,
both threads are waiting for each other to release the lock, the condition is called
deadlock.

Example of Deadlock in java


public class TestDeadlockExample1 {  
public static void main(String[] args) {  
final String resource1 = "ratan jaiswal";  
final String resource2 = "vimal jaiswal";  
// t1 tries to lock resource1 then resource2  
Thread t1 = new Thread() {  
public void run() {  
synchronized (resource1) {  
System.out.println("Thread 1: locked resource 1");  
try { Thread.sleep(100);} catch (Exception e) {}  
synchronized (resource2) {  
System.out.println("Thread 1: locked resource 2");  
}  
}  
}  
};  
// t2 tries to lock resource2 then resource1  
Thread t2 = new Thread() {  
public void run() {  
synchronized (resource2) {  
System.out.println("Thread 2: locked resource 2");  
try { Thread.sleep(100);} catch (Exception e) {}  
synchronized (resource1) {  
System.out.println("Thread 2: locked resource 1");  
}  
}  
 }  
 };  
 t1.start();  
 t2.start();  
 }  
}  

Inter-thread communication in Java

Inter-thread communication or Co-operation is all about allowing synchronized


threads to communicate with each other.

Cooperation (Inter-thread communication) is a mechanism in which a thread is


paused running in its critical section and another thread is allowed to enter (or
lock) in the same critical section to be executed.It is implemented by following
methods of Object class:

 wait()
 notify()
 notifyAll()

1) wait() method

Causes current thread to release the lock and wait until either another thread
invokes the notify() method or the notifyAll() method for this object, or a specified
amount of time has elapsed.

The current thread must own this object's monitor, so it must be called from the
synchronized method only otherwise it will throw exception.

Method Description
public final void wait()throws InterruptedException waits until object is notified.
public final void wait(long timeout)throws waits for the specified amount
InterruptedException of time.

2) notify() method

Wakes up a single thread that is waiting on this object's monitor. If any threads are
waiting on this object, one of them is chosen to be awakened. The choice is
arbitrary and occurs at the discretion of the implementation. Syntax:

public final void notify()

3) notifyAll() method

Wakes up all threads that are waiting on this object's monitor. Syntax:

public final void notifyAll()

Understanding the process of inter-thread communication

The point to point explanation of the above diagram is as follows:

1. Threads enter to acquire lock.


2. Lock is acquired by on thread.
3. Now thread goes to waiting state if you call wait() method on the object.
Otherwise it releases the lock and exits.
4. If you call notify() or notifyAll() method, thread moves to the notified state
(runnable state).
5. Now thread is available to acquire lock.
6. After completion of the task, thread releases the lock and exits the monitor
state of the object.

Why wait(), notify() and notifyAll() methods are defined in Object class not
Thread class?

It is because they are related to lock and object has a lock.

Difference between wait and sleep?

Let's see the important differences between wait and sleep methods.

wait() sleep()
wait() method releases the lock sleep() method doesn't release the lock.
is the method of Object class is the method of Thread class
is the non-static method is the static method
is the non-static method is the static method
should be notified by notify() or after the specified amount of time, sleep
notifyAll() methods is completed.

Daemon Thread in Java:


Daemon thread in java is a service provider thread that provides services to the
user thread. Its life depend on the mercy of user threads i.e. when all the user
threads dies, JVM terminates this thread automatically.
There are many java daemon threads running automatically e.g. gc, finalizer etc.
You can see all the detail by typing the jconsole in the command prompt. The
jconsole tool provides information about the loaded classes, memory usage,
running threads etc.
Methods for Java Daemon thread by Thread class
The java.lang.Thread class provides two methods for java daemon thread.
Method Description
public void setDaemon(boolean is used to mark the current thread as daemon
1)
status) thread or user thread.
2) public booleanisDaemon() is used to check that current is daemon.

Simple example of Daemon thread in java


File: MyThread.java
public class TestDaemonThread1 extends Thread{  
 public void run(){  
f(Thread.currentThread().isDaemon()){//checking for daemon thread  
System.out.println("daemon thread work");  
 }  
  else{  
  System.out.println("user thread work");  
 }  
 }  
 public static void main(String[] args){  
 TestDaemonThread1 t1=new TestDaemonThread1();//creating thread  
 TestDaemonThread1 t2=new TestDaemonThread1();  
 TestDaemonThread1 t3=new TestDaemonThread1();  
  t1.setDaemon(true);//now t1 is daemon thread  
  t1.start();//starting threads  
  t2.start();  
  t3.start();  
 }  
}

You might also like