0% found this document useful (0 votes)
11 views37 pages

Unit 4

The document provides an overview of multithreading in Java, explaining its advantages over multiprocessing, such as shared memory usage and reduced context-switching time. It details the Java Thread class, its methods, and the various states of threads (New, Runnable, Running, Blocked, Dead) during their lifecycle. Additionally, it discusses thread priorities and how they can be set and retrieved in Java programs.

Uploaded by

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

Unit 4

The document provides an overview of multithreading in Java, explaining its advantages over multiprocessing, such as shared memory usage and reduced context-switching time. It details the Java Thread class, its methods, and the various states of threads (New, Runnable, Running, Blocked, Dead) during their lifecycle. Additionally, it discusses thread priorities and how they can be set and retrieved in Java programs.

Uploaded by

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

Unit-IV

Multithreaded Programming: Introduction:

Multithreading in Java
1. Multithreading
2. Multitasking
3. Process-based multitasking
4. Thread-based multitasking
5. What is Thread

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

A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing


and multithreading, both are used to achieve multitasking.

However, we use multithreading than multiprocessing because threads use a shared


memory area. They don't allocate separate memory area so saves memory, and context-
switching between the threads takes less time than process.

Java Multithreading is mostly used in games, animation, etc.

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

A thread is a lightweight sub-process, the smallest unit of processing. Multiprocessing


and multithreading, both are used to achieve multitasking.

However, we use multithreading than multiprocessing because threads use a shared


memory area. They don't allocate separate memory area so saves memory, and context-
switching between the threads takes less time than process.

Java Multithreading is mostly used in games, animation, etc.

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.

Multitasking
Multitasking is a process of executing multiple tasks simultaneously. We use
multitasking to utilize the CPU. Multitasking can be achieved in two ways:

o Process-based Multitasking (Multiprocessing)


o Thread-based Multitasking (Multithreading)

1) Process-based Multitasking (Multiprocessing)


o Each process has an address in memory. In other words, each process allocates a
separate memory area.
o A process is heavyweight.
o Cost of communication between the process is high.
o Switching from one process to another requires some time for saving and
loading registers, memory maps, updating lists, etc.

2) Thread-based Multitasking (Multithreading)


o Threads share the same address space.
o A thread is lightweight.
o Cost of communication between the thread is low.

Java Thread class


Java provides Thread class to achieve thread programming. Thread class
provides constructors and methods to create and perform operations on a thread.
Thread class extends Object class and implements Runnable interface.
Java Thread Methods
S.N Modifier and Type Method Description
.

1) void start() It is used to


start the
execution of
the thread.

2) void run() It is used to


do an action
for a thread.

3) static void sleep() It sleeps a


thread for the
specified
amount of
time.

4) static Thread currentThread() It returns a


reference to
the currently
executing
thread object.

5) void join() It waits for a


thread to die.

6) int getPriority() It returns the


priority of the
thread.

7) void setPriority() It changes


the priority of
the thread.

8) String getName() It returns the


name of the
thread.

9) void setName() It changes


the name of
the thread.

10) long getId() It returns the


id of the
thread.

11) boolean isAlive() It tests if the


thread is
alive.

12) static void yield() It causes the


currently
executing
thread object
to pause and
allow other
threads to
execute
temporarily.

13) void suspend() It is used to


suspend the
thread.

14) void resume() It is used to


resume the
suspended
thread.

15) void stop() It is used to


stop the
thread.

16) void destroy() It is used to


destroy the
thread group
and all of its
subgroups.

17) boolean isDaemon() It tests if the


thread is a
daemon
thread.

18) void setDaemon() It marks the


thread as
daemon or
user thread.

19) void interrupt() It interrupts


the thread.

20) boolean isinterrupted() It tests


whether the
thread has
been
interrupted.

21) static boolean interrupted() It tests


whether the
current
thread has
been
interrupted.

22) static int activeCount() It returns the


number of
active threads
in the current
thread's
thread group.

23) void checkAccess() It determines


if the
currently
running
thread has
permission to
modify the
thread.

24) static boolean holdLock() It returns true


if and only if
the current
thread holds
the monitor
lock on the
specified
object.

25) static void dumpStack() It is used to


print a stack
trace of the
current
thread to the
standard
error stream.
26) StackTraceElement[] getStackTrace() It returns an
array of stack
trace
elements
representing
the stack
dump of the
thread.

27) static int enumerate() It is used to


copy every
active
thread's
thread group
and its
subgroup
into the
specified
array.

28) Thread.State getState() It is used to


return the
state of the
thread.

29) ThreadGroup getThreadGroup() It is used to


return the
thread group
to which this
thread
belongs

30) String toString() It is used to


return a
string
representatio
n of this
thread,
including the
thread's
name,
priority, and
thread group.

31) void notify() It is used to


give the
notification
for only one
thread which
is waiting for
a particular
object.

32) void notifyAll() It is used to


give the
notification
to all waiting
threads of a
particular
object.

33) void setContextClassLoader() It sets the


context
ClassLoader
for the
Thread.

34) ClassLoader getContextClassLoader() It returns the


context
ClassLoader
for the
thread.

35) static getDefaultUncaughtExceptionHandle It returns the


Thread.UncaughtExceptionHandl r() default
er handler
invoked when
a thread
abruptly
terminates
due to an
uncaught
exception.

36) static void setDefaultUncaughtExceptionHandler It sets the


() default
handler
invoked when
a thread
abruptly
terminates
due to an
uncaught

Thread States:

Thread States in Java


A thread is a path of execution in a program that goes through the following states of a
thread. The five states are as follows:

1. New
2. Runnable
3. Running
4. Blocked (Non-runnable state)
5. Dead

New (Newborn State)


When an instance of the Thread class is created a new thread is born and is known to be
in New-born state. That is, when a thread is born, it enters into new state but its
execution phase has not been started yet on the instance.

In simpler terms, Thread object is created but it cannot execute any program statement
because it is not in an execution state of the thread. Only start() method can be called
on a new thread; otherwise, an IllegalThreadStateException will be thrown.

Runnable State
The second phase of a new-born thread is the execution phase. When the start()
method is called on a the new instance of a thread, it enters into a runnable state.
In the runnable state, thread is ready for execution and is waiting for availability of the
processor (CPU time). There are many threads that are ready for execution, they all are
waiting in a queue (line).

If all threads have equal priority, a time slot is assigned for each thread execution on the
basis of first-come, first-serve manner by CPU. The process of allocating time to threads
is known as time slicing. A thread can come into runnable state from running, waiting,
or new states.

Running State
Running means Processor (CPU) has allocated time slot to thread for its execution.
When thread scheduler selects a thread from the runnable state for execution, it goes
into running state. Look at the above figure.

In running state, processor gives its time to the thread for execution and executes its run
method. It is the state where thread performs its actual functions. A thread can come
into running state only from runnable state.

A running thread may give up its control in any one of the following situations and can
enter into the blocked state.
1. When sleep() method is invoked on a thread to sleep for specified time period, the
thread is out of queue during this time period. The thread again reenters into the
runnable state as soon as this time period is elapsed.
2. When a thread is suspended using suspend() method for some time in order to satisfy
some conditions. A suspended thread can be revived by using resume() method.
3. When wait() method is called on a thread to wait for some time. The thread in wait state
can be run again using notify() or notifyAll() method.

Blocked State
A thread is considered to be in the blocked state when it is suspended, sleeping, or
waiting for some time in order to satisfy some condition.

Dead State
A thread dies or moves into dead state automatically when its run() method completes
the execution of statements. That is, a thread is terminated or dead when a thread
comes out of run() method. A thread can also be dead when the stop() method is called.

During the life cycle of thread in Java, a thread moves from one state to another state in
a variety of ways. This is because in multithreading environment, when multiple threads
are executing, only one thread can use CPU at a time.

All other threads live in some other states, either waiting for their turn on CPU or waiting
for satisfying some conditions. Therefore, a thread is always in any of the five states.

Java Thread Program


ThreadDemo.java

1. /* Thread 1 */
2. class Thread1 extends Thread
3. {
4.
5. public void run()
6. {
7. System.out.println("Thread 1");
8. System.out.println("i in Thread 1 ");
9. for (int i = 1; i <= 5; i++)
10. {
11. System.out.println("i = " + i);
12. try
13. {
14. Thread.sleep(1000);
15. }
16. catch (InterruptedException e)
17. {
18. e.printStackTrace();
19. }
20. }
21. System.out.println("Thread 1 Completed.");
22. }
23. }
24.
25. /* Thread 2 */
26. class Thread2 extends Thread
27. {
28. public void run()
29. {
30. System.out.println("Thread 2");
31. System.out.println("i in Thread 2 ");
32. for (int i = 1; i <= 5; i++)
33. {
34. System.out.println("i = " + i);
35. }
36. System.out.println("Thread 2 Completed.");
37. }
38. }
39.
40. /* Driver code */
41. public class ThreadDemo
42. {
43. public static void main(String[] args) {
44. // life cycle of Thread
45. // Thread's New State
46. Thread1 t1 = new Thread1();
47. Thread2 t2 = new Thread2();
48. // Both the above threads are in runnable state
49. // Running state of Thread1 and Thread2
50. t1.start();
51. // Move control to another thread
52. t2.yield();
53. // Blocked State Thread1
54. try
55. {
56. t1.sleep(1000);
57. }
58. catch (InterruptedException e)
59. {
60. e.printStackTrace();
61. }
62. t2.start();
63. System.out.println("Main Thread End");
64. }
65. }

Output:

Thread 1
i in Thread 1
i = 1
Main Thread End
Thread 2
i in Thread 2
i = 1
i = 2
i = 3
i = 4
i = 5
Thread 2 Completed.
i = 2
i = 3
i = 4
i = 5
Thread 1 Completed.

Thread Priority:

Priority of a Thread (Thread Priority)


Each thread has a priority. Priorities are represented by a number between 1 and 10. In
most cases, the thread scheduler schedules the threads according to their priority
(known as preemptive scheduling). But it is not guaranteed because it depends on JVM
specification that which scheduling it chooses. Note that not only JVM a Java
programmer can also assign the priorities of a thread explicitly in a Java program.

Setter & Getter Method of Thread Priority


Let's discuss the setter and getter method of the thread priority.

public final int getPriority(): The java.lang.Thread.getPriority() method returns the


priority of the given thread.

public final void setPriority(int newPriority): The java.lang.Thread.setPriority()


method updates or assign the priority of the thread to newPriority. The method throws
IllegalArgumentException if the value newPriority goes out of the range, which is 1
(minimum) to 10 (maximum).

3 constants defined in Thread class:


1. public static int MIN_PRIORITY
2. public static int NORM_PRIORITY
3. public static int 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.

Example of priority of a Thread:


FileName: ThreadPriorityExample.java

1. // Importing the required classes


2. import java.lang.*;
3.
4. public class ThreadPriorityExample extends Thread
5. {
6.
7. // Method 1
8. // Whenever the start() method is called by a thread
9. // the run() method is invoked
10. public void run()
11. {
12. // the print statement
13. System.out.println("Inside the run() method");
14. }
15.
16. // the main method
17. public static void main(String argvs[])
18. {
19. // Creating threads with the help of ThreadPriorityExample class
20. ThreadPriorityExample th1 = new ThreadPriorityExample();
21. ThreadPriorityExample th2 = new ThreadPriorityExample();
22. ThreadPriorityExample th3 = new ThreadPriorityExample();
23.
24. // We did not mention the priority of the thread.
25. // Therefore, the priorities of the thread is 5, the default value
26.
27. // 1st Thread
28. // Displaying the priority of the thread
29. // using the getPriority() method
30. System.out.println("Priority of the thread th1 is : " + th1.getPriority());
31.
32. // 2nd Thread
33. // Display the priority of the thread
34. System.out.println("Priority of the thread th2 is : " + th2.getPriority());
35.
36. // 3rd Thread
37. // // Display the priority of the thread
38. System.out.println("Priority of the thread th2 is : " + th2.getPriority());
39.
40. // Setting priorities of above threads by
41. // passing integer arguments
42. th1.setPriority(6);
43. th2.setPriority(3);
44. th3.setPriority(9);
45.
46. // 6
47. System.out.println("Priority of the thread th1 is : " + th1.getPriority());
48.
49. // 3
50. System.out.println("Priority of the thread th2 is : " + th2.getPriority());
51.
52. // 9
53. System.out.println("Priority of the thread th3 is : " + th3.getPriority());
54.
55. // Main thread
56.
57. // Displaying name of the currently executing thread
58. System.out.println("Currently Executing The Thread : " + Thread.currentThread().getName());
59.
60. System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());
61.
62. // Priority of the main thread is 10 now
63. Thread.currentThread().setPriority(10);
64.
65. System.out.println("Priority of the main thread is : " + Thread.currentThread().getPriority());
66. }
67. }

Output:

Priority of the thread th1 is : 5


Priority of the thread th2 is : 5
Priority of the thread th2 is : 5
Priority of the thread th1 is : 6
Priority of the thread th2 is : 3
Priority of the thread th3 is : 9
Currently Executing The Thread : main
Priority of the main thread is : 5
Priority of the main thread is : 10

Synchronization, :

Synchronization in Java
Synchronization in Java is the capability to 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.

Why use Synchronization?


The synchronization is mainly used to

1. To prevent thread interference.


2. To prevent consistency problem.

Types of Synchronization
There are two types of synchronization

1. Process Synchronization
2. Thread Synchronization

Here, we will discuss only thread synchronization.

Thread Synchronization
There are two types of thread synchronization mutual exclusive and inter-thread
communication.

1. Mutual Exclusive
1. Synchronized method.
2. Synchronized block.
3. Static synchronization.
2. Cooperation (Inter-thread communication in java)

Mutual Exclusive
Mutual Exclusive helps keep threads from interfering with one another while sharing
data. It can be achieved by using the following three ways:

1. By Using Synchronized Method


2. By Using Synchronized Block
3. By Using Static Synchronization

Concept of Lock in Java


Synchronization is built around an internal entity known as the lock or monitor. Every
object has a 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:

TestSynchronization1.java

1. class Table{
2. void printTable(int n){//method not synchronized
3. for(int i=1;i<=5;i++){
4. System.out.println(n*i);
5. try{
6. Thread.sleep(400);
7. }catch(Exception e){System.out.println(e);}
8. }
9.
10. }
11. }
12.
13. class MyThread1 extends Thread{
14. Table t;
15. MyThread1(Table t){
16. this.t=t;
17. }
18. public void run(){
19. t.printTable(5);
20. }
21.
22. }
23. class MyThread2 extends Thread{
24. Table t;
25. MyThread2(Table t){
26. this.t=t;
27. }
28. public void run(){
29. t.printTable(100);
30. }
31. }
32.
33. class TestSynchronization1{
34. public static void main(String args[]){
35. Table obj = new Table();//only one object
36. MyThread1 t1=new MyThread1(obj);
37. MyThread2 t2=new MyThread2(obj);
38. t1.start();
39. t2.start();
40. }
41. }

Output:

5
100
10
200
15
300
20
400
25
500

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.

TestSynchronization2.java

1. //example of java synchronized method


2. class Table{
3. synchronized void printTable(int n){//synchronized method
4. for(int i=1;i<=5;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){System.out.println(e);}
9. }
10.
11. }
12. }
13.
14. class MyThread1 extends Thread{
15. Table t;
16. MyThread1(Table t){
17. this.t=t;
18. }
19. public void run(){
20. t.printTable(5);
21. }
22.
23. }
24. class MyThread2 extends Thread{
25. Table t;
26. MyThread2(Table t){
27. this.t=t;
28. }
29. public void run(){
30. t.printTable(100);
31. }
32. }
33.
34. public class TestSynchronization2{
35. public static void main(String args[]){
36. Table obj = new Table();//only one object
37. MyThread1 t1=new MyThread1(obj);
38. MyThread2 t2=new MyThread2(obj);
39. t1.start();
40. t2.start();
41. }
42. }

Output:

5
10
15
20
25
100
200
300
400
500

TestSynchronization3.java

1. //Program of synchronized method by using annonymous class


2. class Table{
3. synchronized void printTable(int n){//synchronized method
4. for(int i=1;i<=5;i++){
5. System.out.println(n*i);
6. try{
7. Thread.sleep(400);
8. }catch(Exception e){System.out.println(e);}
9. }
10.
11. }
12. }
13.
14. public class TestSynchronization3{
15. public static void main(String args[]){
16. final Table obj = new Table();//only one object
17.
18. Thread t1=new Thread(){
19. public void run(){
20. obj.printTable(5);
21. }
22. };
23. Thread t2=new Thread(){
24. public void run(){
25. obj.printTable(100);
26. }
27. };
28.
29. t1.start();
30. t2.start();
31. }
32. }

Output:

5
10
15
20
25
100
200
300
400
500

Deadlock and Race Situations,:

Race Condition in Java


Java is a multi-threaded programming language and there is a higher risk to occur race
conditions. Because the same resource may be accessed by multiple threads at the same
time and may change the data. We can say that race condition is a concurrency bug. It
is closely related to deadlock in Java. In this section, we will implement the race
condition in Java

There are two types of race conditions:

1. Read-modify-write
2. Check-then-act

The read-modify-write patterns signify that more than one thread first read the
variable, then alter the given value and write it back to that variable. Let's have a look at
the following code snippet.

1. public class number


2. {
3. protected long number = 0;
4. public void add(long value)
5. {
6. this.number = this.number + value;
7. }
8. }

RaceConditionProgram.java

1. class Counter implements Runnable


2. {
3. private int c = 0;
4. public void increment()
5. {
6. try
7. {
8. Thread.sleep(10);
9. }
10. catch (InterruptedException e)
11. {
12. //Auto-generated catch block
13. e.printStackTrace();
14. }
15. c++;
16. }
17. public void decrement()
18. {
19. c--;
20. }
21. public int getValue()
22. {
23. return c;
24. }
25. @Override
26. public void run()
27. {
28. //incrementing
29. this.increment();
30. System.out.println("Value for Thread After increment " + Thread.currentThread().getNam
e() + " " + this.getValue());
31. //decrementing
32. this.decrement();
33. System.out.println("Value for Thread at last " + Thread.currentThread().getName() + " "
+ this.getValue());
34. }
35. }
36. public class RaceConditionDemo
37. {
38. public static void main(String args[])
39. {
40. Counter counter = new Counter();
41. Thread t1 = new Thread(counter, "Thread-1");
42. Thread t2 = new Thread(counter, "Thread-2");
43. Thread t3 = new Thread(counter, "Thread-3");
44. t1.start();
45. t2.start();
46. t3.start();
47. }
48. }

Output:

Value for Thread After increment Thread-1 2


Value for Thread at last Thread-1 2
Value for Thread After increment Thread-3 3
Value for Thread at last Thread-3 1
Value for Thread After increment Thread-2 2
Value for Thread at last Thread-2 0

Inter-thread Communication –:

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:

o wait()
o notify()
o notifyAll()

1) wait() method
The 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 It waits until object is notified.

public final void wait(long timeout)throws It waits for the specified amount of
InterruptedException time.

2) notify() method
The 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:

1. public final void notify()


3) notifyAll() method
Wakes up all threads that are waiting on this object's monitor.

Syntax:

1. 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()

The wait() method releases the lock. The sleep() method doesn't release the lock.

It is a method of Object class It is a method of Thread class

It is the non-static method It is the static method

It should be notified by notify() or notifyAll() methods After the specified amount of time, sleep is completed.

Example of Inter Thread Communication in Java


Let's see the simple example of inter thread communication.

Test.java

1. class Customer{
2. int amount=10000;
3.
4. synchronized void withdraw(int amount){
5. System.out.println("going to withdraw...");
6.
7. if(this.amount<amount){
8. System.out.println("Less balance; waiting for deposit...");
9. try{wait();}catch(Exception e){}
10. }
11. this.amount-=amount;
12. System.out.println("withdraw completed...");
13. }
14.
15. synchronized void deposit(int amount){
16. System.out.println("going to deposit...");
17. this.amount+=amount;
18. System.out.println("deposit completed... ");
19. notify();
20. }
21. }
22.
23. class Test{
24. public static void main(String args[]){
25. final Customer c=new Customer();
26. new Thread(){
27. public void run(){c.withdraw(15000);}
28. }.start();
29. new Thread(){
30. public void run(){c.deposit(10000);}
31. }.start();
32.
33. }}

Output:

going to withdraw...
Less balance; waiting for deposit...
going to deposit...
deposit completed...
withdraw completed

Suspending, Resuming, and Stopping of Threads.:

Java Thread suspend() method


The suspend() method of thread class puts the thread from running to waiting state.
This method is used if you want to stop the thread execution and start it again when a
certain event occurs. This method allows a thread to temporarily cease execution. The
suspended thread can be resumed using the resume() method.

Syntax
1. public final void suspend()

Return
This method does not return any value.

Exception
SecurityException: If the current thread cannot modify the thread.

Example
1. public class JavaSuspendExp extends Thread
2. {
3. public void run()
4. {
5. for(int i=1; i<5; i++)
6. {
7. try
8. {
9. // thread to sleep for 500 milliseconds
10. sleep(500);
11. System.out.println(Thread.currentThread().getName());
12. }catch(InterruptedException e){System.out.println(e);}
13. System.out.println(i);
14. }
15. }
16. public static void main(String args[])
17. {
18. // creating three threads
19. JavaSuspendExp t1=new JavaSuspendExp ();
20. JavaSuspendExp t2=new JavaSuspendExp ();
21. JavaSuspendExp t3=new JavaSuspendExp ();
22. // call run() method
23. t1.start();
24. t2.start();
25. // suspend t2 thread
26. t2.suspend();
27. // call run() method
28. t3.start();
29. }
30. }
Test it Now

Output:

Thread-0
1
Thread-2
1
Thread-0
2
Thread-2
2
Thread-0
3
Thread-2
3
Thread-0
4
Thread-2
4

Life cycle of a Thread (Thread States)


In Java, a thread always exists in any one of the following states. These states are:

1. New
2. Active
3. Blocked / Waiting
4. Timed Waiting
5. Terminated

Explanation of Different Thread States


New: Whenever a new thread is created, it is always in the new state. For a thread in the
new state, the code has not been run yet and thus has not begun its execution.

Active: When a thread invokes the start() method, it moves from the new state to the
active state. The active state contains two states within it: one is runnable, and the other
is running.

o Runnable: A thread, that is ready to run is then moved to the runnable state. In the
runnable state, the thread may be running or may be ready to run at any given instant of
time. It is the duty of the thread scheduler to provide the thread time to run, i.e., moving
the thread the running state.
A program implementing multithreading acquires a fixed slice of time to each individual
thread.
o Running: When the thread gets the CPU, it moves from the runnable to the running
state. Generally, the most common change in the state of a thread is from runnable to
running and again back to runnable.

Blocked or Waiting: Whenever a thread is inactive for a span of time (not permanently)
then, either the thread is in the blocked state or is in the waiting state.

Timed Waiting: Sometimes, waiting for leads to starvation. For example, a thread (its
name is A) has entered the critical section of a code and is not willing to leave that
critical section. In such a scenario, another thread (its name is B) has to wait forever,
which leads to starvation. To avoid such scenario, a timed waiting state is given to
thread B. Thus, thread lies in the waiting state for a specific span of time, and not
forever. A real example of timed waiting is when we invoke the sleep() method on a
specific thread. The sleep() method puts the thread in the timed wait state. After the
time runs out, the thread wakes up and start its execution from when it has left earlier.

Terminated: A thread reaches the termination state because of the following reasons:

o When a thread has finished its job, then it exists or terminates normally.
o Abnormal termination: It occurs when some unusual events such as an unhandled
exception or segmentation fault.

A terminated thread means the thread is no more in the system. In other words, the
thread is dead, and there is no way one can respawn (active after kill) the dead thread.

The following diagram shows the different states involved in the life cycle of a thread.

Implementation of Thread States


In Java, one can get the current state of a thread using the Thread.getState() method.
The java.lang.Thread.State class of Java provides the constants ENUM to represent the
state of a thread. These constants are:

1. public static final Thread.State NEW

It represents the first state of a thread that is the NEW state.

1. public static final Thread.State RUNNABLE

It represents the runnable state.It means a thread is waiting in the queue to run.

1. public static final Thread.State BLOCKED


It represents the blocked state. In this state, the thread is waiting to acquire a lock.

1. public static final Thread.State WAITING

It represents the waiting state. A thread will go to this state when it invokes the
Object.wait() method, or Thread.join() method with no timeout. A thread in the waiting
state is waiting for another thread to complete its task.

1. public static final Thread.State TIMED_WAITING

It represents the timed waiting state. The main difference between waiting and timed
waiting is the time constraint. Waiting has no time constraint, whereas timed waiting has
the time constraint. A thread invoking the following method reaches the timed waiting
state.

o sleep
o join with timeout
o wait with timeout
o parkUntil
o parkNanos

1. public static final Thread.State TERMINATED

It represents the final state of a thread that is terminated or dead. A terminated thread
means it has completed its execution.

Java Threads | How to create a thread in Java


There are two ways to create a thread:

1. By extending Thread class


2. By implementing Runnable interface.

Thread class:
Thread class provide constructors and methods to create and perform operations on a
thread.Thread class extends Object class and implements Runnable interface.
Commonly used Constructors of Thread class:
o Thread()
o Thread(String name)
o Thread(Runnable r)
o Thread(Runnable r,String name)

Commonly used methods of Thread class:


1. public void run(): is used to perform action for a thread.
2. public void start(): starts the execution of the thread.JVM calls the run() method on the
thread.
3. public void sleep(long miliseconds): Causes the currently executing thread to sleep
(temporarily cease execution) for the specified number of milliseconds.
4. public void join(): waits for a thread to die.
5. public void join(long miliseconds): waits for a thread to die for the specified
miliseconds.
6. public int getPriority(): returns the priority of the thread.
7. public int setPriority(int priority): changes the priority of the thread.
8. public String getName(): returns the name of the thread.
9. public void setName(String name): changes the name of the thread.
10. public Thread currentThread(): returns the reference of currently executing thread.
11. public int getId(): returns the id of the thread.
12. public Thread.State getState(): returns the state of the thread.
13. public boolean isAlive(): tests if the thread is alive.
14. public void yield(): causes the currently executing thread object to temporarily pause
and allow other threads to execute.
15. public void suspend(): is used to suspend the thread(depricated).
16. public void resume(): is used to resume the suspended thread(depricated).
17. public void stop(): is used to stop the thread(depricated).
18. public boolean isDaemon(): tests if the thread is a daemon thread.
19. public void setDaemon(boolean b): marks the thread as daemon or user thread.
20. public void interrupt(): interrupts the thread.
21. public boolean isInterrupted(): tests if the thread has been interrupted.
22. public static boolean interrupted(): tests if the current thread has been interrupted.

Runnable interface:
The Runnable interface should be implemented by any class whose instances are
intended to be executed by a thread. Runnable interface have only one method named
run().

1. public void run(): is used to perform action for a thread.

Starting a thread:
The start() method of Thread class is used to start a newly created thread. It performs
the following tasks:

o A new thread starts(with new callstack).


o The thread moves from New state to the Runnable state.
o When the thread gets a chance to execute, its target run() method will run.

1) Java Thread Example by extending Thread class


FileName: Multi.java

1. class Multi extends Thread{


2. public void run(){
3. System.out.println("thread is running...");
4. }
5. public static void main(String args[]){
6. Multi t1=new Multi();
7. t1.start();
8. }
9. }

Output:

thread is running...
2) Java Thread Example by implementing Runnable interface
FileName: Multi3.java

1. class Multi3 implements Runnable{


2. public void run(){
3. System.out.println("thread is running...");
4. }
5.
6. public static void main(String args[]){
7. Multi3 m1=new Multi3();
8. Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
9. t1.start();
10. }
11. }

Output:

thread is running...

You might also like