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

Multithreading Java

Multithreading in Java allows multiple threads to execute simultaneously, enhancing performance and responsiveness in applications. The document outlines the advantages of multithreading, the lifecycle of threads, methods for creating threads, and the differences between extending the Thread class and implementing the Runnable interface. Additionally, it discusses the thread scheduler, scheduling algorithms, and the use of the sleep() method to control thread execution timing.

Uploaded by

ishikajanit
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Multithreading Java

Multithreading in Java allows multiple threads to execute simultaneously, enhancing performance and responsiveness in applications. The document outlines the advantages of multithreading, the lifecycle of threads, methods for creating threads, and the differences between extending the Thread class and implementing the Runnable interface. Additionally, it discusses the thread scheduler, scheduling algorithms, and the use of the sleep() method to control thread execution timing.

Uploaded by

ishikajanit
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 33

Multithreading in Java

Multithreading in Java is a process of executing multiple threads


simultaneously.

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

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.

What is Thread in java


A thread is a lightweight subprocess, the smallest unit of processing. It is a
separate path of execution.

Threads are independent. If there occurs exception in one thread, it doesn't


affect other threads. It uses a shared memory area.

Note: At a time one thread is executed only.

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.

1
Java Thread Methods

S.N Modifier Method Description


. and Type

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 currentThread() It returns a reference to the


Thread 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.

2
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 interrupted() It tests whether the current thread


boolean 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 holdLock() It returns true if and only if the


boolean 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

3
error stream.

26) StackTraceEl getStackTrace() It returns an array of stack trace


ement[] 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.Stat getState() It is used to return the state of the


e thread.

29) ThreadGrou getThreadGroup() It is used to return the thread


p group to which this thread belongs

30) String toString() It is used to return a string


representation 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 getDefaultUncaughtEx It returns the default handler


Thread.Unca ceptionHandler() invoked when a thread abruptly
ughtExcepti terminates due to an uncaught
onHandler exception.

36) static void setDefaultUncaughtExc It sets the default handler invoked


eptionHandler() when a thread abruptly terminates
due to an uncaught exception.

4
Lifecycle and States of a Thread in Java
A thread in Java at any point of time exists in any one of the following states.
A thread lies only in one of the shown states at any instant:
1. New State
2. Runnable State
3. Blocked State
4. Waiting State
5. Timed Waiting State
6. Terminated State

The diagram shown below represents various states of a thread at any


instant in time.

Life Cycle of a Thread


There are multiple states of the thread in a lifecycle as mentioned below:
1. New Thread: When a new thread is created, it is in the new state. The
thread has not yet started to run when the thread is in this state. When a
thread lies in the new state, its code is yet to be run and hasn’t started to
execute.
2. Runnable State: A thread that is ready to run is moved to a runnable
state. In this state, a thread might actually be running or it might be
ready to run at any instant of time. It is the responsibility of the thread
scheduler to give the thread, time to run.
A multi-threaded program allocates a fixed amount of time to each
individual thread. Each and every thread runs for a short while and then
pauses and relinquishes the CPU to another thread so that other threads
can get a chance to run. When this happens, all such threads that are
ready to run, waiting for the CPU and the currently running thread lie in a
runnable state.

5
3. Blocked: The thread will be in blocked state when it is trying to acquire a
lock but currently the lock is acquired by the other thread. The thread will
move from the blocked state to runnable state when it acquires the lock.
4. Waiting state: The thread will be in waiting state when it calls wait()
method or join() method. It will move to the runnable state when other
thread will notify or that thread will be terminated.
5. Timed Waiting: A thread lies in a timed waiting state when it calls a
method with a time-out parameter. A thread lies in this state until the
timeout is completed or until a notification is received. For example, when
a thread calls sleep or a conditional wait, it is moved to a timed waiting
state.
6. Terminated State: A thread terminates because of either of the
following reasons:

 Because it exits normally. This happens when the code of the thread
has been entirely executed by the program.
 Because there occurred some unusual erroneous event, like a
segmentation fault or an unhandled exception.

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.

Thread creation by extending the Thread class

We create a class that extends the java.lang.Thread class. This class


overrides the run() method available in the Thread class. A thread begins
its life inside run() method. 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.

6
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. }

Java Multiple Threads Example by extending Thread class

1. public class Test extends Thread {


2. public void run() {
3. try {
4. System.out.println("Thread with thread id:
"+Thread.currentThread().getId()+" is running");
5. }
6. catch(Exception e) {}
7.
8. }
9.
10. public static void main(String[] args) {
11. // TODO Auto-generated method stub
12.
13. for(int i=1;i<6;i++) {
14. Test obj = new Test();
15. obj.start();
16. }
17. }
18.
19. }

7
2) Java Thread Example by implementing 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().

If you are not extending the Thread class, your class object would
not be treated as a thread object. So you need to explicitly create
the Thread class object. We are passing the object of your class that
implements Runnable so that your class run() method may execute.

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. 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...

8
Java Multiple Threads Example by implementing Runnable
interface

12. public class Test implements Runnable {


13. public void run() {
14. try {
15. System.out.println("Thread with thread id:
"+Thread.currentThread().getId()+" is running");
16. }
17. catch(Exception e) {}
18. }
19. public static void main(String[] args) {
20. // TODO Auto-generated method stub
21. for(int i=1;i<6;i++) {
22. Test obj = new Test();
23. Thread thr = new Thread(obj);
24. thr.start();
25. }
26. }
27. }

3) Using the Thread Class: Thread(String Name)

We can directly use the Thread class to spawn new threads using the constructors
defined above.
public class MyThread1
1. {
2. // Main method
3. public static void main(String argvs[])
4. {
5. // creating an object of the Thread class using the constructor Thread(String
name)
6. Thread t= new Thread("My first thread");
7.
8. // the start() method moves the thread to the active state

9
9. t.start();
10. // getting the thread name by invoking the getName() method
11. String str = t.getName();
12. System.out.println(str);
13. }
14. }

4) Using the Thread Class: Thread(Runnable r, String name)


Observe the following program.

FileName: MyThread2.java

1. public class MyThread2 implements Runnable


2. {
3. public void run()
4. {
5. System.out.println("Now the thread is running ...");
6. }
7.
8. // main method
9. public static void main(String argvs[])
10. {
11. // creating an object of the class MyThread2
12. Runnable r1 = new MyThread2();
13.
14. // creating an object of the class Thread using Thread(Runnable r, Strin
g name)
15. Thread th1 = new Thread(r1, "My new thread");
16.
17. // the start() method moves the thread to the active state
18. th1.start();
19.
20. // getting the thread name by invoking the getName() method
21. String str = th1.getName();
22. System.out.println(str);
23. }

10
24. }

Output:

My new thread
Now the thread is running ...

Thread Class vs Runnable Interface


1. If we extend the Thread class, our class cannot extend any other class
because Java doesn’t support multiple inheritance. But, if we implement
the Runnable interface, our class can still extend other base classes.
2. We can achieve basic functionality of a thread by extending Thread class
because it provides some inbuilt methods like yield(), interrupt() etc. that
are not available in Runnable interface.
3. Using runnable will give you an object that can be shared amongst
multiple threads.

Thread Scheduler in Java


A component of Java that decides which thread to run or execute and which
thread to wait is called a thread scheduler in Java. In Java, a thread is only
chosen by a thread scheduler if it is in the runnable state. However, if there
is more than one thread in the runnable state, it is up to the thread
scheduler to pick one of the threads and ignore the other ones. There are
some criteria that decide which thread will execute first. There are two
factors for scheduling a thread i.e. Priority and Time of arrival.

Priority: Priority of each thread lies between 1 to 10. If a thread has a


higher priority, it means that thread has got a better chance of getting
picked up by the thread scheduler.

Time of Arrival: Suppose two threads of the same priority enter the
runnable state, then priority cannot be the factor to pick a thread from these
two threads. In such a case, arrival time of thread is considered by the
thread scheduler. A thread that arrived first gets the preference over the
other threads.

Thread Scheduler Algorithms


On the basis of the above-mentioned factors, the scheduling algorithm is
followed by a Java thread scheduler.

First Come First Serve Scheduling:


11
Time-slicing scheduling:
Usually, the First Come First Serve algorithm is non-preemptive, which is bad
as it may lead to infinite blocking (also known as starvation). To avoid that,
some time-slices are provided to the threads so that after some time, the
running thread has to give up the CPU. Thus, the other waiting threads also
get time to run their job.

Working of the Java Thread Scheduler

Thread.sleep() in Java with Examples


The Java Thread class provides the two variant of the sleep() method. First one
accepts only an arguments, whereas the other variant accepts two arguments. The
method sleep() is being used to halt the working of a thread for a given amount of
time. The time up to which the thread remains in the sleeping state is known as the
sleeping time of the thread. After the sleeping time is over, the thread starts its
execution from where it has left.

The sleep() Method Syntax:


Following are the syntax of the sleep() method.

1. public static void sleep(long mls) throws InterruptedException

12
The Thread.sleep() method can be used with any thread. It means any other thread
or the main thread can invoke the sleep() method.

Parameters:
The following are the parameters used in the sleep() method.

mls: The time in milliseconds is represented by the parameter mls. The


duration for which the thread will sleep is given by the method sleep().

Important Points to Remember About the Sleep() Method


Whenever the Thread.sleep() methods execute, it always halts the execution
of the current thread.

Whenever another thread does interruption while the current thread is


already in the sleep mode, then the InterruptedException is thrown.

If the system that is executing the threads is busy, then the actual sleeping
time of the thread is generally more as compared to the time passed in
arguments. However, if the system executing the sleep() method has less
load, then the actual sleeping time of the thread is almost equal to the time
passed in the argument.

Example of the sleep() method in Java : on the custom thread


The following example shows how one can use the sleep() method on the
custom thread.

FileName: TestSleepMethod1.java

1. class TestSleepMethod1 extends Thread{


2. public void run(){
3. for(int i=1;i<5;i++){
4. // the thread will sleep for the 500 milli seconds
5. try{Thread.sleep(500);}catch(InterruptedException e)
{System.out.println(e);}
6. System.out.println(i);
7. }
8. }
9. public static void main(String args[]){
10. TestSleepMethod1 t1=new TestSleepMethod1();
11. TestSleepMethod1 t2=new TestSleepMethod1();
12.

13
13. t1.start();
14. t2.start();
15. }
16. }

Java Thread Priority in Multithreading


Priorities in threads is a concept where each thread is having a priority which
in layman’s language one can say every object is having priority here which
is represented by numbers ranging from 1 to 10.
 The default priority is set to 5 as excepted.
 Minimum priority is set to 1.
 Maximum priority is set to 10.

Let us do discuss how to get and set priority of a thread in java.


1. public final int getPriority(): java.lang.Thread.getPriority() method
returns priority of given thread.
2. public final void setPriority(int
newPriority): java.lang.Thread.setPriority() method changes the
priority of thread to the value newPriority. This method throws
IllegalArgumentException if value of parameter newPriority goes beyond
minimum(1) and maximum(10) limit.

Example

// Java Program to Illustrate Priorities in Multithreading


// via help of getPriority() and setPriority() method
// Importing required classes
import java.lang.*;
// Main class
class ThreadDemo extends Thread {
// Method 1
// run() method for the thread that is called
// as soon as start() is invoked for thread in main()
public void run()
{
// Print statement
System.out.println("Inside run method");
}
// Main driver method
public static void main(String[] args)
{
// Creating random threads
// with the help of above class

14
ThreadDemo t1 = new ThreadDemo();
ThreadDemo t2 = new ThreadDemo();
ThreadDemo t3 = new ThreadDemo();
// Thread 1
// Display the priority of above thread
// using getPriority() method
System.out.println("t1 thread priority : "+ t1.getPriority());
// Thread 1
// Display the priority of above thread
System.out.println("t2 thread priority : "+ t2.getPriority());
// Thread 3
System.out.println("t3 thread priority : "+ t3.getPriority());
// Setting priorities of above threads by
// passing integer arguments
t1.setPriority(2);
t2.setPriority(5);
t3.setPriority(8);

// t3.setPriority(21); will throw


// IllegalArgumentException
// 2
System.out.println("t1 thread priority : "+ t1.getPriority());
// 5
System.out.println("t2 thread priority : "+ t2.getPriority());
// 8
System.out.println("t3 thread priority : "+ t3.getPriority());
// Main thread
// Displays the name of
// currently executing Thread
System.out.println("Currently Executing Thread : "+
Thread.currentThread().getName());

System.out.println("Main thread priority : "+


Thread.currentThread().getPriority());

// Main thread priority is set to 10


Thread.currentThread().setPriority(10);

System.out.println("Main thread priority : "+


Thread.currentThread().getPriority());
}
}

Main thread in Java

15
When a Java program starts up, one thread begins running immediately. This
is usually called the main thread of our program because it is the one that is
executed when our program begins.
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:

How to control Main thread


The main thread is created automatically when our program is started. To
control it we must obtain a reference to it. This can be done by calling the
method currentThread( ) which is present in Thread class. This method
returns a reference to the thread on which it is called. The default priority of
Main thread is 5 and for all remaining user threads priority will be inherited
from parent to child.

Example

16
// Java program to control the Main Thread Importing required classes
import java.io.*;
import java.util.*;
// Class 1 Main class extending thread class
public class Test extends Thread {
// Main driver method
public static void main(String[] args)
{
// Getting reference to Main thread
Thread t = Thread.currentThread();
// Getting name of Main thread
System.out.println("Current thread: "+ t.getName());
// Changing the name of Main thread
t.setName("Geeks");
System.out.println("After name change: " + t.getName());
// Getting priority of Main thread
System.out.println("Main thread priority: "+ t.getPriority());
// Setting priority of Main thread to MAX(10)
t.setPriority(MAX_PRIORITY);
// Print and display the main thread priority
System.out.println("Main thread new priority: "+ t.getPriority());
for (int i = 0; i < 5; i++) {
System.out.println("Main thread");
}
// Main thread creating a child thread
Thread ct = new Thread() {
// run() method of a thread
public void run()
{
for (int i = 0; i < 5; i++) {
System.out.println("Child thread");
}
}
};

// Getting priority of child thread which will be inherited from


Main thread as it is created by Main thread
System.out.println("Child thread priority: "+ ct.getPriority());
// Setting priority of Main thread to MIN(1)
ct.setPriority(MIN_PRIORITY);
System.out.println("Child thread new priority: "+ ct.getPriority());
// Starting child thread
ct.start();
}
}

17
// Class 2
// Helper class extending Thread class
// Child Thread class
class ChildThread extends Thread {
@Override public void run()
{
for (int i = 0; i < 5; i++) {

// Print statement whenever child thread is called


System.out.println("Child thread");
}
}
}

What does start() function do in multithreading in


Java?
The purpose of start() is to create a separate call stack for the thread. A
separate call stack is created by it, and then run() is called by JVM. When a
program calls the start() method, a new thread is created and then
the run() method is executed. But if we directly call the run() method then no
new thread will be created and run() method will be executed as a normal
method call on the current calling thread itself and no multi-threading will
take place.

Let us see what happens if we don’t call start() and rather call run()
directly. We have modified the first

// Java code to see that all threads are pushed on same stack if we use run()
instead of start().
class ThreadTest 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");
}

18
}
}
// Main Class
public class Main
{
public static void main(String[] args)
{
int n = 8;
for (int i=0; i<n; i++)
{
ThreadTest object = new ThreadTest();

// start() is replaced with run() for


// seeing the purpose of start
object.run();
}
}
}
Output:

Thread 1 is running
Thread 1 is running
Thread 1 is running
Thread 1 is running
Thread 1 is running
Thread 1 is running
Thread 1 is running
Thread 1 is running

Now, let us try to call run() method directly instead of start() method:
class MyThread extends Thread {
public void run()
{
System.out.println("Current thread name: "
+ Thread.currentThread().getName());

System.out.println("run() method called");


}
}

class GeeksforGeeks {
public static void main(String[] args)

19
{
MyThread t = new MyThread();
t.run();
}
}
Output:
Current thread name: main
run() method called

1. Multiple invocation: In Java’s multi-threading concept, another most


important difference between start() and run() method is that we can’t
call the start() method twice otherwise it will throw
an IllegalStateException whereas run() method can be called multiple
times as it is just a normal method calling. Let us understand it with an
example:

start() run()

Creates a new thread and the run() No new thread is created and the
method is executed on the newly run() method is executed on the
created thread. calling thread itself.

Can’t be invoked more than one time


otherwise Multiple invocation is possible
throws java.lang.IllegalStateException

Defined
in java.lang.Runnable interface
Defined in java.lang.Thread class.
and must be overridden in the
implementing class.

Joining Threads in Java


java.lang.Thread class provides the join() method which allows one thread
to wait until another thread completes its execution. 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.

There are three overloaded join functions.

20
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:
2. public final void join()
3. 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:
4. public final synchronized void join(long millis)
5. 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).
Syntax:
public final synchronized void join(long millis, int
nanos)

// Java program to explain the


// concept of joining a thread.
import java.io.*;

// Creating thread by creating the


// objects of that class
class ThreadJoining extends Thread
{
@Override
public void run()
{
for (int i = 0; i < 2; i++)
{
try
{
Thread.sleep(500);
System.out.println("Current Thread: "
+ Thread.currentThread().getName());
}

catch(Exception ex)
{
System.out.println("Exception has" +
" been caught" + ex);
}
System.out.println(i);
}

21
}
}

class GFG
{
public static void main (String[] args)
{

// creating two threads


ThreadJoining t1 = new ThreadJoining();
ThreadJoining t2 = new ThreadJoining();
ThreadJoining t3 = new ThreadJoining();

// thread t1 starts
t1.start();

// starts second thread after when


// first thread t1 has died.
try
{
System.out.println("Current Thread: "
+ Thread.currentThread().getName());
t1.join();
}

catch(Exception ex)
{
System.out.println("Exception has " +
"been caught" + ex);
}

// t2 starts
t2.start();

// starts t3 after when thread t2 has died.


try
{
System.out.println("Current Thread: "
+ Thread.currentThread().getName());
t2.join();
}

catch(Exception ex)
{
System.out.println("Exception has been" +
" caught" + ex);

22
}

t3.start();
}
}

output:
Current Thread: main
Current Thread: Thread-0
0
Current Thread: Thread-0
1
Current Thread: main
Current Thread: Thread-1
0
Current Thread: Thread-1
1
Current Thread: Thread-2
0
Current Thread: Thread-2
1

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.

Points to remember for Daemon Thread in Java


o It provides services to user threads for background supporting tasks. It
has no role in life than to serve user threads.
o Its life depends on user threads.
o It is a low priority thread.

23
Why JVM terminates the daemon thread if there is no user
thread?
The sole purpose of the daemon thread is that it provides services to user
thread for background supporting task. If there is no user thread, why should
JVM keep running this thread. That is why JVM terminates the daemon thread
if there is no user thread.

Methods for Java Daemon thread by Thread class


The java.lang.Thread class provides two methods for java daemon thread.

No. Method Description

1) public void is used to mark the current thread as daemon


setDaemon(boolean thread or user thread.
status)

2) public boolean isDaemon() is used to check that current is daemon.

Simple example of Daemon thread in java

1. public class TestDaemonThread1 extends Thread{


2. public void run(){
3. if(Thread.currentThread().isDaemon()){//checking for daemon thread
4. System.out.println("daemon thread work");
5. }
6. else{
7. System.out.println("user thread work");
8. }
9. }
10. public static void main(String[] args){
11. TestDaemonThread1 t1=new TestDaemonThread1();//creating threa
d
12. TestDaemonThread1 t2=new TestDaemonThread1();
13. TestDaemonThread1 t3=new TestDaemonThread1();
14.
15. t1.setDaemon(true);//now t1 is daemon thread

24
16.
17. t1.start();//starting threads
18. t2.start();
19. t3.start();
20. }
21. }

Output:

daemon thread work


user thread work
user thread work

Note: If you want to make a user thread as Daemon, it must not be started otherwise
it will throw IllegalThreadStateException.

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.

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.

25
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


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. class MyThread1 extends Thread{
11. Table t;
12. MyThread1(Table t){
13. this.t=t;
14. }
15. public void run(){
16. t.printTable(5);

26
17. } }
18. class MyThread2 extends Thread{
19. Table t;
20. MyThread2(Table t){
21. this.t=t;
22. }
23. public void run(){
24. t.printTable(100);
25. } }
26. class TestSynchronization1{
27. public static void main(String args[]){
28. Table obj = new Table();//only one object
29. MyThread1 t1=new MyThread1(obj);
30. MyThread2 t2=new MyThread2(obj);
31. t1.start();
32. t2.start();
33. } }

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.

1. class Table{

27
2. synchronized 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. class MyThread1 extends Thread{
11. Table t;
12. MyThread1(Table t){
13. this.t=t;
14. }
15. public void run(){
16. t.printTable(5);
17. } }
18. class MyThread2 extends Thread{
19. Table t;
20. MyThread2(Table t){
21. this.t=t;
22. }
23. public void run(){
24. t.printTable(100);
25. } }
26. class TestSynchronization1{
27. public static void main(String args[]){
28. Table obj = new Table();//only one object
29. MyThread1 t1=new MyThread1(obj);
30. MyThread2 t2=new MyThread2(obj);
31. t1.start();
32. t2.start();
33. } }

Output:

5
10
15
20

28
25
100
200
300
400
500

Synchronized Block in Java


Synchronized block can be used to perform synchronization on any specific
resource of the method.

Suppose we have 50 lines of code in our method, but we want to synchronize


only 5 lines, in such cases, we can use synchronized block.

If we put all the codes of the method in the synchronized block, it will work
same as the synchronized method.

Points to Remember

o Synchronized block is used to lock an object for any shared resource.


o Scope of synchronized block is smaller than the method.
o A Java synchronized block doesn't allow more than one JVM, to provide access
control to a shared resource.
o The system performance may degrade because of the slower working of
synchronized keyword.
o Java synchronized block is more efficient than Java synchronized method.

Syntax

1. synchronized (object reference expression) {


2. //code block
3. }

1. class Table
2. {
3. void printTable(int n){
4. synchronized(this){//synchronized block
5. for(int i=1;i<=5;i++){

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

Output:
37. 5
38. 10
39. 15
40. 20
41. 25
42. 100
43. 200

30
44. 300
45. 400
46. 500

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 It waits until object is notified.


InterruptedException

public final void wait(long timeout)throws It waits for the specified


InterruptedException amount of 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

31
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.

Example of Inter Thread Communication in Java


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

class Customer{
int amount=10000;

synchronized void withdraw(int amount){


System.out.println("going to withdraw...");

if(this.amount<amount){
System.out.println("Less balance; waiting for deposit...");
try{wait();}catch(Exception e){}
}
this.amount-=amount;
System.out.println("withdraw completed...");
}

synchronized void deposit(int amount){


System.out.println("going to deposit...");
this.amount+=amount;
System.out.println("deposit completed... ");
notify();
}
}

//Threads Thread 1
public class ThreadforWithdrawl extends Thread {
Customer c;
int amount;

public ThreadforWithdrawl(Customer c, int amount) {


// TODO Auto-generated constructor stub
this.c =c;
this.amount=amount;
}
public void run() {

32
c.withdraw(amount);
}
}

//Thread thread 2
public class ThreadforDeposit extends Thread{

Customer c;
int amount;

public ThreadforDeposit(Customer c, int amount) {


// TODO Auto-generated constructor stub
this.c =c;
this.amount=amount;
}
public void run() {
c.deposit(amount);
}
}

// test Class
public class Test {

public static void main(String[] args) {


// TODO Auto-generated method stub

Customer c= new Customer();

ThreadforWithdrawl thrwithdraw = new


ThreadforWithdrawl(c, 50000);

ThreadforDeposit thrdeposit = new ThreadforDeposit(c,


10000);

thrwithdraw.start();

thrdeposit.start();

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

33

You might also like