0% found this document useful (0 votes)
5 views23 pages

Module 5 Java1 (1)

Download as pdf or txt
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 23

MODULE-5 MULTITHREADED PROGRAMMING

MODULE 5
Chapter-1
 Multi-Threaded Programming:
The Java Thread Model,
The Main Thread,
Creating a Thread,
Creating Multiple Threads,
MULTI- Using isAlive() and join(),
THREADED Thread Priorities,
Synchronization,
PROGRAMMING Interthread Communication,
Suspending, Resuming, and Stopping Threads,
and Obtaining a Thread’s State.
ENUMERATIONS, Enumerations, Type Wrappers and Autoboxing
 Enumerations (Enumeration Fundamentals, The
TYPE WRAPPERS AND
values() and valueOf() Methods),
AUTOBOXING:  Type Wrappers (Character, Boolean, The Numeric
Type Wrappers),
 Autoboxing (Autoboxing and Methods,
Autoboxing/Unboxing Occurs in Expressions,
 Autoboxing/Unboxing Boolean and Character
Values).

1
MODULE-5 MULTITHREADED PROGRAMMING

Multi-Threaded Programming
 Multithreading in Java is a process of executing multiple threads simultaneously for
maximum utilization of CPU.
 Each part of such a program is called a thread.
 Multithreading is used to achieve multitasking.
 There are two distinct types of multitasking:
Process based multitasking.
Thread-based multitasking.
 Process-based multitasking (Multiprocessing):
Process-based multitasking is to run two or more programs concurrently
Each process has an address in memory. In other words, each processallocates
a separate memory area.
 Thread-based multitasking (Multithreading):
In thread-based multitasking, a single program can perform two or more tasks
simultaneously.
Threads share the same address space.

What are threads?


 Thread can be defined as a sub process with lightweight (or) smallest unit of process in
execution.
 Java provides built-in support for multithreaded programming.
 A multithreaded program contains two or more parts that can run concurrently.
 Each part of such a program is called a thread, and each thread defines a separate path of
execution.
 Thus, multithreading is a specialized form of multitasking.
 Multithreading enables you to write very efficient programs that make maximum use of
the CPU,because idle time can be kept to a minimum. Multitasking threads require less
overhead than multitasking processes.

Thread Model/Thread states/Life cycle of thread


A thread in Java at any point of time exists in any one of the following states. A thread lies only
in one ofthe shown states at any instant:

 New:
The thread is in new state if you create an instance of Thread class but before the
invocation ofstart() method.
 Runnable
The thread is in runnable state after invocation of start() method, but the thread scheduler

2
MODULE-5 MULTITHREADED PROGRAMMING

has not selected it to be the running thread.


 Blocked
This is the state when the thread is still alive, but is currently not eligible to run.

 WAITING:
A thread enters this state if it waits to be notified by another thread, which is the result of
calling Object.wait( ) or Thread.join( ).
The thread also enters waiting state if it waits for a Lock or Condition in the
java.util.concurrent package.
When another thread calls Objects notify()/notifyAll() or Condition‟s signal()/signalAll(),
the thread comes back to the runnable state.
 Timed-Waiting
A thread enters this state if a method with timeout parameter is called: sleep(), wait(),
join(), Lock.tryLock() and Condition.await(). The thread exits this state if the timeout
expires or the appropriate notification has been received.
 Terminated
A thread enters terminated state when it has completed execution. The thread terminates
for one of two reasons:
o The run( ) method exits normally.
o The run() method exits abruptly due to a uncaught exception occurs.

What is Main Thread?

As we create Main Method in each and every Java Program, which acts as an entry point for the code to get
executed by JVM.
Similarly in this Multithreading Concept, Each Program has one Main Thread which was provided by default
by JVM, hence whenever a program is being created in java.
3
MODULE-5 MULTITHREADED PROGRAMMING

The main thread is automatically created when a Java program starts.


The default priority of Main thread is 5.

There are certain properties associated with the main thread which are as follows:
 It is the thread from which other “child” threads will be spawned.
 Often, it must be the last thread to finish execution because it performs various shutdown actions

The flow diagram is as follows:

Example
1. import :
java.util.*;
2. public class MainThreadExample
3. {
4. public static void main(String[] args)
{
5. Thread t=new thread();
System.out.println("Start of main thread, current thread is" +t);
t.setName(“mythread”);
System.out.println(“after the change: “+t);
6. try
{
for(int i=5;i>0;i--)
{
System.out.println(i);
7. Thread.sleep(1000); // in milliseconds
}
}
catch (InterruptedException e)
{
System.out.println(“main thread interrupted”);
}
} 4
}
MODULE-5 MULTITHREADED PROGRAMMING

Output:
Start of main thread, current thread is Thread[main,5,main]
After the change: Thread[mythread,5,main]

How to make the classes threadable


Java defines two ways in which this can be accomplished:
 By implementing the Runnable interface.
 By extending the Thread class

Implementing the Runnable Interface


To create a thread is to create a class that implements the Runnable interface.
 Runnable abstracts a unit of executable code.
 Construct a thread on any object that implements Runnable.
 To implement Runnable, a class need only implement a single method called run( )
 Syntax;
public void run( )
 run( ) method introduces a concurrent thread into your program. This thread will end
when run( ) method terminates.
 we must specify the code that our thread will execute inside run() method.
 run( ) method can call other methods, can use other classes and declare variables just
like any other normal method.
 Example:
class first implements Runnable

public void run( )

System.out.println("Thread started ..");

public class Multithreading

public static void main(String [ ] args)

first obj=new first( ); //or – Thread t1=new Thread ( new first ( ) ) ;


Thread t1 = new Thread ( obj );
t1.start( ) ; Thread started ..

 To call the run( ) method, start( ) method is used.


On calling start( ), a new stack is provided to the thread and run( ) method is called to introduce the new thread into
the program

5
MODULE-5 MULTITHREADED PROGRAMMING

Extending Thread class


 Create a thread by a new class that extends Thread class and create an instance of that class.
 The extending class must override run( ) method which is the entry point of new thread.
 We create an object of our new class and call start() method to start the execution of a thread.
Start() invokes the run() method on the Thread object.
 Example:

class first extends Thread

public void run( )

System.out.println("Thread started ..");

public class Multithreading

public static void main(String [ ] args)


Thread started ..
first t1=new first();
t1.start( ) ;

Creating multiple threads:

Multithreading in Java is a process of executing multiple threads simultaneously.


Advantages of Java Multithreading
1) It doesn't block the user because threads are independent and you can perform multiple operations at the
same time.
2) You can perform many operations together, so it saves time.
3) Threads are independent, so it doesn't affect other threads if an exception occurs in a single thread.
class MultithreadingDemo extends Thread
{
public void run()
{
try {
// Displaying the thread that is running
System.out.println( "Thread " + Thread.currentThread().getId() + " is
running");
}
catch (Exception e)
{
// Throwing an exception
System.out.println("Exception is caught");
}
}
}
6
// Main Class
public class Multithread
MODULE-5
{ MULTITHREADED PROGRAMMING
public static void main(String[] args) Output:
{
for (int i = 0; i < 5; i++) Thread 15 is running
{
Thread 14 is running
MultithreadingDemo object = new MultithreadingDemo();
object.start(); Thread 12 is running
}
Thread 11 is running
}
} Thread 13 is running

isAlive() function

 It is used to check if a thread is alive or not.


 Alive refers to a thread that has began but not been terminated yet. When the run method is called, the
thread operates for a specific period of time after which it stops executing.
Syntax
public final boolean isAlive()
This method will return true if the thread is alive otherwise returns false.
1. public class IsAliveExp extends Thread
2. {
3. public void run()
4. {
5. try
6. {
7. Thread.sleep(300);
8. System.out.println("is run() method isAlive "+Thread.currentThread().isAlive());
9. }
catch (InterruptedException ie) {
} Output:
} before starting thread isAlive: false
after starting thread isAlive: true
public static void main(String[] args) is run() method isAlive true
{
IsAliveExp t1 = new IsAliveExp();
System.out.println("before starting thread isAlive: "+t1.isAlive());
t1.start();
System.out.println("after starting thread isAlive: "+t1.isAlive());
}
}

Join() method
 java.lang.Thread class provides the join() method which allows one thread to wait until another
thread completes its execution.

7
MODULE-5 MULTITHREADED PROGRAMMING

 If t is a Thread object whose thread is currently executing, then t.join() will make sure that t is
terminated before the next instruction is executed by the program.
 If there are multiple threads calling the join() methods that means overloading on join allows the
programmer to specify a waiting period.
 However join is dependent on the OS for timing, so you should not assume that join will wait
exactly as long as you specify.
There are three overloaded join functions.
1. join(): It will put the current thread on wait until the thread on which it is called is dead. If thread is
interrupted then it will throw InterruptedException.
Syntax:
public final void join()
2. join(long millis) :It will put the current thread on wait until the thread on which it is called is dead or
wait for specified time (milliseconds).
Syntax:
public final synchronized void join(long millis)
3. join(long millis, int nanos): It will put the current thread on wait until the thread on which it is called
is dead or wait for specified time (milliseconds + nanos).
4. Syntax:
public final synchronized void join(long millis, int nanos)
Example 1
1. import java.io.*;
2. // The ThreadJoin class is the child class of the class Thread
3. class ThreadJoin extends Thread
4. {
public void run() // overriding the run method
{
for (int j = 0; j < 2; j++)
{
try
{
5. // sleeping the thread for 300 milli seconds
Thread.sleep(300);
System.out.println("The current thread name is: " + Thread.currentThread().getName());
}
6. // catch block for catching the raised exception
catch(Exception e)
{
System.out.println("The exception has been caught: " + e);
}
System.out.println( j );
}
8
}
7. }
MODULE-5 MULTITHREADED PROGRAMMING

1. public class ThreadJoinExample


2. {
public static void main (String argvs[])
{
3. ThreadJoin th1 = new ThreadJoin(); // creating 3 threads
ThreadJoin th2 = new ThreadJoin();
ThreadJoin th3 = new ThreadJoin();
th1.start(); // thread th1 starts
4. // starting the second thread after when the first thread th1 has ended or died
try
{
System.out.println("The current thread name is: "+ Thread.currentThread().getName());
th1.join(); // invoking the join() method
}
5. // catch block for catching the raised exception
catch(Exception e)
{
System.out.println("The exception has been caught " + e);
}
6. th2.start(); // thread th2 starts
7. // starting the th3 thread after when the thread th2 has ended or died.
try
{
System.out.println("The current thread name is: " + Thread.currentThread().getName());
th2.join();
}
8. // catch block for catching the raised exception
catch(Exception e)
{
System.out.println("The exception has been caught " + e);
}
9. th3.start(); // thread th3 starts
}
}

9
MODULE-5 MULTITHREADED PROGRAMMING
Output:
The current thread name is: main
The current thread name is: Thread - 0 Explanation: The above program shows that the
0 second thread th2 begins after the first thread th1
The current thread name is: Thread - 0 has ended, and the thread th3 starts its work after
1
The current thread name is: main the second thread th2 has ended or died.
The current thread name is: Thread - 1
0
The current thread name is: Thread - 1
1
The current thread name is: Thread - 2
0
The current thread name is: Thread - 2
1

Synchronization
 When two or more threads need access to a shared resource, they need some way to ensure that the
resource will be used by only one thread at a time. The process by which this is achieved is called
synchronization.

 Key to synchronization is the concept of the monitor (also called a semaphore). Amonitor is an
object that is used as a mutually exclusive lock, or mutex.

 Only one thread can own a monitor at a given time.

 When a thread acquires a lock, it is said to have entered the monitor.

 All other threads attempting to enter the locked monitor will be suspended until the first thread exits
the monitor.

 These other threads are said to be waiting for the monitor. A thread that owns a monitor can re enter
the same monitor if it so desires.

 Let us try to understand the problem without synchronization. Here, in the following example to
threads are accessing the same resource (object) to print the Table. The Table class contains one
method, printTable(int ), which actually prints the table. We are creating two Threads, Thread1 and
Thread2, which are using the same instance of the Table Resource (object), to print the table. When
one thread is using the resource, no other thread is allowed to access the same resource Table to print
the table.

Example without the synchronization:


Class Table
{

void printTable(int n)
{ //method not synchronized
for(int i=1;i<=5;i++)
{
10
MODULE-5 MULTITHREADED PROGRAMMING

System.out.println(n*i);
try{
Thread.sleep(400);
}
catch(InterruptedException ie)
{
System.out.println("The Exception is :"+ie);
}
}
} //end of the printTable() method
}

class MyThread1 extends Thread


{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}
} //end of the Thread1

class MyThread2 extends Thread


{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}
} //end of Thread2

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();
}
}

11
MODULE-5 MULTITHREADED PROGRAMMING

The output for the above program will be as follow:


Output: 5
100
10
200
15
300
20
400
25
500
In the above output, it can be observed that both the threads are simultaneously accessing the Table
object to print the table. Thread1 prints one line and goes to sleep, 400 milliseconds, and Thread1
prints its task.

Using the 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.
The general form of the synchronized method is:
synchronized type method_name(para_list)
{
//body of the method
}

where synchronized is the keyword, method contains the type, and method_name represents the
name of the method, and para_list indicate the list of the parameters.

Example using the synchronized method

Class Table
{

synchronized void printTable(int n)


{ //method not synchronized
for(int i=1;i<=5;i++)
{
System.out.println(n*i);
try{
12
MODULE-5 MULTITHREADED PROGRAMMING

Thread.sleep(400);
}
catch(InterruptedException ie)

System.out.println("The Exception is :"+ie);


}
}
} //end of the printTable() method
}

class MyThread1 extends Thread


{
Table t;
MyThread1(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(5);
}
} //end of the Thread1

class MyThread2 extends Thread


{
Table t;
MyThread2(Table t)
{
this.t=t;
}
public void run()
{
t.printTable(100);
}
} //end of Thread2

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();
}
}
13
MODULE-5 MULTITHREADED PROGRAMMING

Output: 5
10
15
20
25
100
200
300
400
500

In the above output it can be observed that when Thread1 is accessing the Table object, Thread2 is not
allowed to access it. Thread1 preempts the Thread2 from accessing the printTable() method.

Note:
This way of communications between the threads competing for same resource is
called implicit communication.
This has one disadvantage due to polling. The polling wastes the CPU time. To save
the CPU time, it is preferred to go to the inter-thread communication.

Example-2
package jk;

public class Test


{
public static void main(String[] args)
{
Sample obj=new Sample();
Thread1 t1=new Thread1(obj);
Thread2 t2=new Thread2(obj);

t1.start();
t2.start();
}
}

14
MODULE-5 MULTITHREADED PROGRAMMING

package jk;

public class Sample


{
synchronized void print(int n) //synchronized method
{
for(int i=1;i<=5;i++)
{
System.out.println(n+i);
try{ Thread.sleep(500); }
catch(Exception e){ System.out.println(e); }
}
}
}

package jk;

public class Thread1 extends Thread


{
Sample s;
Thread1(Sample s)
{
this.s=s;
}
public void run()
{
s.print(10);
}
}

package jk;

public class Thread2 extends Thread


{
Sample s;
Thread2(Sample s)
{
this.s=s;
}
public void run()
{
s.print(50);
}
}
Output:

Without Thread Synchronization (Random output with both threads – we will getdifferent outputs with
different runs)

Run1 Run2 Run3

11 51 51
51 11 11
52 52 52
12 12 12
53 13 53
13 53 13
15
MODULE-5 MULTITHREADED PROGRAMMING

54 54 14
14 14 54
55 55 15
15 15 55

With Thread Synchronization (Always gets same output that is Thread1 followed byThread2)

11
12
13
14
15
51
52
53
54

Thread Priorities
Thread priorities are used by the thread scheduler to decide when each thread should be allowed
to run.
In theory, higher-priority threads get more CPU time than lower-priority threads. In practice, the
amount of CPU time that a thread gets often depends on several factors besides its priority. A
higher-priority thread can also preempt a lower-priority one.
3 constants defined in Thread class:
1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int MAX_PRIORITY

To set a thread’s priority, use the setPriority( ) method, which is a member of Thread.
This is its general form:
final void setPriority(int level)

Here, level specifies the new priority setting for the calling thread. The value of level must be
within the range MIN_PRIORITY and MAX_PRIORITY.

Default priority of a thread is 5 (NORM_PRIORITY). The value of MIN_PRIORITY is 1 and the value of
MAX_PRIORITY is 10.

You can obtain the current priority setting by calling the getPriority( ) method of Thread,
shown here:

final int getPriority( )


16
MODULE-5 MULTITHREADED PROGRAMMING

Example Program:

//setting the priorities for the thread


class PThread1 extends Thread
{
public void run()
{
System.out.println(" Child 1 is started");
}
}
class PThread2 extends Thread
{
public void run()
{
System.out.println(" Child 2 is started");
}
}
class PThread3 extends Thread
{
public void run()
{
System.out.println(" Child 3 is started");
}
} Output:
Child 2 is started
class PTest Child 3 is started
{ Child 1 is started
public static void main(String args[]) The pt1 thread priority is :1
{
//setting the priorities to the thread using the setPriority() method
PThread1 pt1=new PThread1();
pt1.setPriority(1);
PThread2 pt2=new PThread2();
pt2.setPriority(9);
PThread3 pt3=new PThread3();
pt3.setPriority(6);
pt1.start();
pt2.start();
pt3.start();
//getting the priority
System.out.println("The pt1 thread priority is :"+pt1.getPriority());
}
}

17
MODULE-5 MULTITHREADED PROGRAMMING

Inter-Thread Communication

If two or more Threads are communicating with each other, it is called "inter thread"
communication.
Using the synchronized method, two or more threads can communicate indirectly.
Through, synchronized method, each thread always competes for the resource. This way of
competing is called polling(In polling client send requests to server at intervals to check the
status of a running job.).
The polling wastes the much of the CPU valuable time. The better solution to this problem is, just
notify other threads for the resource, when the current thread has finished its task. This is explicit
communication between the threads.
Java addresses this polling problem, using via wait(), notify(), and notifyAll() methods. These
methods are implemented as final methods in Object, so all classes have them.
All three methods can be called only from within a synchronized context.

 wait( ) tells the calling thread to give up the monitor and go to sleep until some 
other thread enters the same monitor and calls notify( ).
 notify( ) wakes up a thread that called wait( ) on the same object.
 notifyAll( ) wakes up all the threads that called wait( ) on the same object. One of 
the threads will be granted access.

These methods are declared within Object, as shown here:

final void wait( ) throws InterruptedException


final void notify( )
final void notifyAll( )
Additional forms of wait( ) exist that allow you to specify a period of time to wait.

Although wait( ) normally waits until notify( ) or notifyAll( ) is called.

18
MODULE-5 MULTITHREADED PROGRAMMING

Example program for producer and consumer problemclass Q


import java.util.Scanner;

public class threadexample


{
public static void main(String[] args) throws InterruptedException
{
final PC pc = new PC();

// Create a thread object that calls pc.produce()


Thread t1 = new Thread(new Runnable() );
{
public void run()
{
try
{
pc.produce();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}

19
// Create another thread object that calls // pc.consume()
MODULE-5 MULTITHREADED PROGRAMMING
Thread t2 = new Thread(new Runnable());
{
public void run()
{
try
{
pc.consume();
}
catch(InterruptedException e)
{
e.printStackTrace();
}
}
}
t1.start();// Start both threads
t2.start();
t1.join();// t1 finishes before t2
t2.join();
}

// PC (Produce Consumer) class with produce() and // consume() methods.

public static class PC


{
// Prints a string and waits for consume()
public void produce()throws InterruptedException
{
// synchronized block ensures only one thread // running at a time
. synchronized(this)
{
System.out.println("producer thread running");

wait();// releases the lock on shared resource // and waits till some other method invokes notify().
System.out.println("Resumed");
}
}

// Sleeps for some time and waits for a key press. After key // is pressed, it notifies produce().

public void consume()throws InterruptedException


{
Thread.sleep(1000); // this makes the produce thread to run first.
Scanner s = new Scanner(System.in);
Output:
// synchronized block ensures only one thread // running at a time.
synchronized(this) producer thread running
{
System.out.println("Waiting for return key."); Waiting for return key.
s.nextLine();
System.out.println("Return key pressed"); Return key pressed

// notifies the produce thread that it // can wake up. Resumed


notify();

Thread.sleep(2000); // Sleep

} 20
}
MODULE-5 MULTITHREADED PROGRAMMING

Explanation:
1. In the main class, a new PC object is created.
2. It runs produce and consume methods of PC objects using two different threads, namely t1 and t2, and
waits for these threads to finish.
Let’s understand how our produce and consume method works.
 The use of a synchronized block ensures that only one thread at a time runs. Also, since there is a sleep

method just at the beginning of consume loop, the producing thread gets a start.
 When the wait is called in produce method, it does two things. Firstly it releases the lock it holds on the
PC object. Secondly, it makes the produce thread go on a waiting state until all other threads have
terminated. It can again acquire a lock on a PC object, and some other method wakes it up by i nvoking
notify or notifyAll on the same object.
 Therefore we see that as soon as the wait is called, the control transfers to consume thread, and it prints
-“Waiting for return key.”
 After we press the return key, consume method invokes notify(). It also does two things- Firstly, unlike
wait(), it does not release the lock on shared resources therefore for getting the desired result, it is
advised to use notify only at the end of your method. Secondly, it notifies the waiting threads that they
can now wake up but only after the current method terminates.
 As you might have observed that even after notifying, the control does not immediately pass over to the
produce thread. The reason for it is that we have called Thread.sleep() after notify(). We already know
that the consume thread is holding a lock on a PC object. Another thread cannot access it until it has
released the lock. Hence only after the consume thread finishes its sleep time and after that terminates
by itself, the produce thread cannot take back the control.
 After a 2 second pause, the program terminates to its completion.

Suspending, Blocking and Stopping Threads

 Whenever we want stop a thread we can stop from running using "stop()" method of thread
class. It's general form will be as follows:
 Thread.stop();
 This method causes a thread to move from running to dead state. A thread will also move
to dead state automatically when it reaches the end of its method.
Blocking Thread
 A thread can be temporarily suspended or blocked from entering into the runnable and running
state by using the following methods:
21
MODULE-5 MULTITHREADED PROGRAMMING

sleep() —blocked for specified time


suspend() ----blocked until further orders
wait() --blocked until certain condition occurs
 These methods cause the thread to go into the blocked state. The thread will return to the
runnable state when the specified time is elapsed in the case of sleep(), the resume()
method is invoked in the case of suspend(), and the notify() method is called in the case
of wait().

Example program:
// Using suspend() and resume().

1. public class JavaResumeExp extends Thread


2. {
3. public void run()
Output:
4. { Thread-0
5. for(int i=1; i<5; i++) 1
Thread-2
6. {
1
7. try Thread-1
8. { 1
Thread-0
9. sleep(500); // thread to sleep for 500 milliseconds 2
10. System.out.println(Thread.currentThread().getName()); Thread-2
11. }catch(InterruptedException e){System.out.println(e);}
2
Thread-1
12. System.out.println(i); 2
13. } Thread-0
3
14. }
Thread-2
15. public static void main(String args[]) 3
16. { Thread-1
3
17. JavaResumeExp t1=new JavaResumeExp (); // creating three threads Thread-0
18. JavaResumeExp t2=new JavaResumeExp (); 4
19. JavaResumeExp t3=new JavaResumeExp ();
Thread-2
4
20. t1.start(); // call run() method Thread-1
21. t2.start(); 4
22. t2.suspend(); // suspend t2 thread
t3.start(); // call run() method
23. t2.resume(); // resume t2 thread
t1.stop();//stop t1 thread
}
} 22
MODULE-5 MULTITHREADED
PROGRAMMING

Obtaining a thread state in java


A thread lifecycle defines the different states of the thread. A thread can be in five major
states:

1. New
2. Runnable
3. Running
4. Non-Runnable (Blocked)
5. Terminated

getState() method

The getState() method of the Thread class is an instance method that returns the state of the
thread object on which this method is invoked.

Syntax

public State getState()

Parameters
The method has no parameters.

Return value
This method returns an enum State that has the following values:

1. NEW: The thread has not yet started execution.


2. RUNNABLE: A thread in execution.
3. BLOCKED: A thread in a blocked state.
4. WAITING: A thread in a waiting state.
5. TIMED_WAITING: A state for a waiting thread with a specified waiting time.
6. TERMINATED: The thread is terminated.

public class ThreadDemo implements Runnable


{
public void run()
{
// returns the state of this thread
Thread.State state = Thread.currentThread().getState();
System.out.println(Thread.currentThread().getName());
System.out.println("state = " + state);
}
Output:
public static void main(String args[])
{ Thread-0
Thread t = new Thread(new ThreadDemo()); state = RUNNABLE
// this will call run() function
t.start();
}
}

23

You might also like