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

Multi Threading

- Multithreading in Java allows executing multiple threads simultaneously by using lightweight subprocesses called threads that can achieve multitasking. - Threads are more efficient than processes for multitasking because threads share memory while processes have separate memory areas, reducing memory usage and context switching time. - Common uses of multithreading include games, animations, and performing multiple operations simultaneously to save time while individual threads remain unaffected by exceptions in other threads.

Uploaded by

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

Multi Threading

- Multithreading in Java allows executing multiple threads simultaneously by using lightweight subprocesses called threads that can achieve multitasking. - Threads are more efficient than processes for multitasking because threads share memory while processes have separate memory areas, reducing memory usage and context switching time. - Common uses of multithreading include games, animations, and performing multiple operations simultaneously to save time while individual threads remain unaffected by exceptions in other threads.

Uploaded by

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

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

Keep Watching

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.

Note: At least one process is required for each 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.
As shown in the above figure, a thread is executed inside the process. There is context-
switching between the threads. There can be multiple processes inside the OS, and one
process can have multiple threads.

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. Each and every thread runs for a short span of time and when that allocated time
slice is over, the thread voluntarily gives up the CPU to the other thread, so that the
other threads can also run for their slice of time. Whenever such a scenario occurs, all
those threads that are willing to run, waiting for their turn to run, lie in the runnable
state. In the runnable state, there is a queue where the threads lie.
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.

How to find Nth Highest Salary in SQL

For example, a thread (let's say its name is A) may want to print some data from the
printer. However, at the same time, the other thread (let's say its name is B) is using the
printer to print some data. Therefore, thread A has to wait for thread B to use the
printer. Thus, thread A is in the blocked state. A thread in the blocked state is unable to
perform any execution and thus never consume any cycle of the Central Processing Unit
(CPU). Hence, we can say that thread A remains idle until the thread scheduler
reactivates thread A, which is in the waiting or blocked state.
When the main thread invokes the join() method then, it is said that the main thread is
in the waiting state. The main thread then waits for the child threads to complete their
tasks. When the child threads complete their job, a notification is sent to the main
thread, which again moves the thread from waiting to the active state.

If there are a lot of threads in the waiting or blocked state, then it is the duty of the
thread scheduler to determine which thread to choose and which one to reject, and the
chosen thread is then given the opportunity to run.

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

How to find Nth Highest Salary in SQL

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

public class MyClass extends Thread

public void run()

System.out.println("thread is running...");

public static void main(String args[])

MyClass t1=new MyClass();

t1.start();
}

}Output:

thread is running...

2) Java Thread Example by implementing Runnable


interface
FileName: Multi3.java

class Multi3 implements Runnable


{
public void run()
{
System.out.println("thread is running...");
}

public static void main(String args[]){


Multi3 m1=new Multi3();
Thread t1 =new Thread(m1); // Using the constructor Thread(Runnable r)
t1.start();
}
}

Sleep method in java


The sleep() method of Thread class is used to sleep a thread for the specified amount of
time.

Syntax of sleep() method in java


The Thread class provides two methods for sleeping a thread:

o public static void sleep(long miliseconds)throws InterruptedException


o public static void sleep(long miliseconds, int nanos)throws InterruptedException
class SleepDemo extends Thread
{
public void run()
{
for(int i=1;i<=5;i++)
{
try
{
System.out.println(i);

Thread.sleep(500);
}
catch(InterruptedException e)
{
System.out.println(e);
}
}
}
public static void main(String args[])
{
SleepDemo t1=new SleepDemo();
SleepDemo t2=new SleepDemo();
t1.start();
t2.start();
}
}

1)Thread class
import java.util.*;
import java.io.*;
class Slip2_1 extends Thread
{
String s1;
Slip2_1(String s)
{
s1=s;
start();
}
public void run()
{
System.out.println("Vowels are ");
for(int i=0;i<s1.length();i++)
{

try
{
char ch=s1.charAt(i);
if(ch=='a'||ch=='e'||ch=='i'||ch=='o'||
ch=='u'||ch=='A'||ch=='E'||ch=='I'||ch=='O'||ch=='U')
System.out.println(" "+ch);
Thread.sleep(1500);
}
catch(InterruptedException e)
{
System.out.println(e);
}

}
}
public static void main(String a[]) throws Exception
{
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
System.out.println("Enter a string");
String str=br.readLine();
Slip2_1 v=new Slip2_1(str);
}
}

2)import java.io.BufferedReader;
import java.io.InputStreamReader;

class SleepDemo implements Runnable


{
int i,no;
SleepDemo(int n)
{
no = n;
}
public void run()
{
for(i = 1; i<=no; i++)
{
System.out.println("\nHello Java");
try
{
Thread.sleep(1000);
}
catch(Exception e)
{
System.out.println(e);
}
}
}
public static void main(String args[])
{
try
{
int n;
System.out.println("\nEnter Number : ");
BufferedReader br = new BufferedReader(new
InputStreamReader(System.in));
n = Integer.parseInt(br.readLine());
SleepDemo s1=new SleepDemo(n)
Thread t = new Thread(s1);
t.start();
}
catch(Exception e)
{
e.printStackTrace();
}
}

}
Can we start a thread twice
No. After starting a thread, it can never be started again. If you does so,
an IllegalThreadStateException is thrown. In such case, thread will run once but for
second time, it will throw exception.

public class TestThreadTwice1 extends Thread{


public void run(){
System.out.println("running...");
}
public static void main(String args[]){
TestThreadTwice1 t1=new TestThreadTwice1();
t1.start();
t1.start();
} }
running
Exception in thread "main" java.lang.IllegalThreadStateException

The join() method


The join() method waits for a thread to die. In other words, it causes the currently
running threads to stop executing until the thread it joins with completes its task.

Syntax:
public void join()throws InterruptedException

public void join(long milliseconds)throws InterruptedException

class TestJoinMethod1 extends Thread{


public void run(){
for(int i=1;i<=5;i++){
try{
Thread.sleep(500);
}catch(Exception e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
TestJoinMethod1 t1=new TestJoinMethod1();
TestJoinMethod1 t2=new TestJoinMethod1();
TestJoinMethod1 t3=new TestJoinMethod1();
t1.start();
try{
t1.join();
}catch(Exception e){System.out.println(e);}
t2.start();
t3.start();
}
}
Output:1
2
3
4
5
1
1
2
2
3
3
4
4
5
5

As you can see in the above example,when t1 completes its task then t2 and t3 starts executing.

Example of join(long miliseconds) method

class TestJoinMethod2 extends Thread{


public void run(){
for(int i=1;i<=5;i++){
try{
Thread.sleep(500);
}catch(Exception e){System.out.println(e);}
System.out.println(i);
}
}
public static void main(String args[]){
TestJoinMethod2 t1=new TestJoinMethod2();
TestJoinMethod2 t2=new TestJoinMethod2();
TestJoinMethod2 t3=new TestJoinMethod2();
t1.start();
try{
t1.join(1500);
}catch(Exception e){System.out.println(e);}

t2.start();
t3.start();
}
}
Output:1
2
3
1
4
1
2
5
2
3
3
4
4
5
5

In the above example,when t1 is completes its task for 1500 miliseconds(3 times) then t2 and t3 starts
executing.

getName(),setName(String) and getId() method:

public String getName()


public void setName(String name)
public long getId()
class TestJoinMethod3 extends Thread{
public void run(){
System.out.println("running...");
}
public static void main(String args[]){
TestJoinMethod3 t1=new TestJoinMethod3();
TestJoinMethod3 t2=new TestJoinMethod3();
System.out.println("Name of t1:"+t1.getName());
System.out.println("Name of t2:"+t2.getName());
System.out.println("id of t1:"+t1.getId());
System.out.println("id of t1:"+t2.getId());
t1.start();
t2.start();

t1.setName("abcd");
System.out.println("After changing name of t1:"+t1.getName());
t2.setName("abcdefr");
System.out.println("After changing name of t1:"+t2.getName());
}
}
The currentThread() method:
The currentThread() method returns a reference to the currently executing thread
object.

Syntax:
public static Thread currentThread()

Example of currentThread() method

1. class TestJoinMethod4 extends Thread{


2. public void run(){
3. System.out.println(Thread.currentThread().getName());
4. }
5. }
6. public static void main(String args[]){
7. TestJoinMethod4 t1=new TestJoinMethod4();
8. TestJoinMethod4 t2=new TestJoinMethod4();
9.
10. t1.start();
11. t2.start();
12. }
13. }
Test it Now
Output:Thread-0
Thread-1

Priority of a Thread (Thread Priority):


Each thread have a priority. Priorities are represented by a number between 1 and 10. In most cases,
thread schedular 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.
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:

class TestMultiPriority1 extends Thread{


public void run(){
System.out.println("running thread name is:"+Thread.currentThread().getName());
System.out.println("running thread priority is:"+Thread.currentThread().getPriority());

}
public static void main(String args[]){
TestMultiPriority1 m1=new TestMultiPriority1();
TestMultiPriority1 m2=new TestMultiPriority1();
m1.setPriority(Thread.MIN_PRIORITY);
m2.setPriority(Thread.MAX_PRIORITY);
m1.start();
m2.start();

}
}

What if we call Java run() method


directly instead start() method?
o Each thread starts in a separate call stack.
o Invoking the run() method from the main thread, the run() method goes onto the current
call stack rather than at the beginning of a new call stack.
FileName: TestCallRun1.java

class TestCallRun1 extends Thread{


public void run(){
System.out.println("running...");
}
public static void main(String args[]){
TestCallRun1 t1=new TestCallRun1();
t1.run();//fine, but does not start a separate call stack
}
}

Output:

running...

Problem if you direct call run() method

FileName: TestCallRun2.javay

1. class TestCallRun2 extends Thread{


2. public void run(){
3. for(int i=1;i<5;i++){
4. try{Thread.sleep(500);}catch(InterruptedException e){System.out.println(e);}
5. System.out.println(i);
6. }
7. }
8. public static void main(String args[]){
9. TestCallRun2 t1=new TestCallRun2();
10. TestCallRun2 t2=new TestCallRun2();
11.
12. t1.run();
13. t2.run();
14. }
15. }
Test it Now

Output:

1
2
3
4
1
2
3
4

As we can see in the above program that there is no context-switching because here t1
and t2 will be treated as normal object not thread object.

Daemon Thread in Java


Daemon thread in Java is a service provider thread that provides services to the user
thread. Its life depend on the mercy of user threads i.e. when all the user threads dies,
JVM terminates this thread automatically.

There are many java daemon threads running automatically e.g. gc, finalizer etc.

You can see all the detail by typing the console in the command prompt. The console
tool provides information about the loaded classes, memory usage, running threads 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.

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.

26.6M

616

Features of Java - Javatpoint

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 setDaemon(boolean is used to mark the current thread as daemon thread or
status) user thread.

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

Simple example of Daemon thread in java


File: MyThread.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 thread
12. TestDaemonThread1 t2=new TestDaemonThread1();
13. TestDaemonThread1 t3=new TestDaemonThread1();
14.
15. t1.setDaemon(true);//now t1 is daemon thread
16.
17. t1.start();//starting threads
18. t2.start();
19. t3.start();
20. }
21. }
Test it Now

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.

File: MyThread.java
1. class TestDaemonThread2 extends Thread{
2. public void run(){
3. System.out.println("Name: "+Thread.currentThread().getName());
4. System.out.println("Daemon: "+Thread.currentThread().isDaemon());
5. }
6.
7. public static void main(String[] args){
8. TestDaemonThread2 t1=new TestDaemonThread2();
9. TestDaemonThread2 t2=new TestDaemonThread2();
10. t1.start();
11. t1.setDaemon(true);//will throw exception here
12. t2.start();
13. }
14. }
Test it Now

Output:

exception in thread main: java.lang.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.

Types of Synchronization
There are two types of synchronization 27.1M

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

class Table{
void printTable(int n){//method not synchronized
for(int i=1;i<=10;i++){
System.out.println(n*i);
try{
Thread.sleep(400);
}catch(Exception e){System.out.println(e);}
}

}
}

class MyThread1 extends Thread{


Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}

}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}

class TestSynchronization1{
public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}

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

//example of java synchronized method


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

}
}

class MyThread1 extends Thread{


Table t;
MyThread1(Table t){
this.t=t;
}
public void run(){
t.printTable(5);
}

}
class MyThread2 extends Thread{
Table t;
MyThread2(Table t){
this.t=t;
}
public void run(){
t.printTable(100);
}
}

public class TestSynchronization2{


public static void main(String args[]){
Table obj = new Table();//only one object
MyThread1 t1=new MyThread1(obj);
MyThread2 t2=new MyThread2(obj);
t1.start();
t2.start();
}
}

Output:

5
10
15
20
25
100
200
300
400
500

Example of synchronized method by using


annonymous class
In this program, we have created the two threads by using the anonymous class, so less
coding is required.

TestSynchronization3.java

//Program of synchronized method by using annonymous class


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

public class TestSynchronization3{


public static void main(String args[]){
final Table obj = new Table();//only one object

Thread t1=new Thread(){


public void run(){
obj.printTable(5);
}
};
Thread t2=new Thread(){
public void run(){
obj.printTable(100);
}
};

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

Output:

5
10
15
20
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. }

Example of Synchronized Block


Let's see the simple example of synchronized block.

Competitive questions on Structures in Hindi


Keep Watching

TestSynchronizedBlock1.java

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

Output:

5
10
15
20
25
100
200
300
400
500

Static Synchronization
If you make any static method as synchronized, the lock will be on the class not on
object.

Problem without static synchronization


Suppose there are two objects of a shared class (e.g. Table) named object1 and object2.
In case of synchronized method and synchronized block there cannot be interference
between t1 and t2 or t3 and t4 because t1 and t2 both refers to a common object that
have a single lock. But there can be interference between t1 and t3 or t2 and t4 because
t1 acquires another lock and t3 acquires another lock. We don't want interference
between t1 and t3 or t2 and t4. Static synchronization solves this problem.

Example of Static Synchronization


In this example we have used synchronized keyword on the static method to perform
static synchronization.

TestSynchronization4.java

21.3M

452

Java Try Catch

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

Output:

1
2
3
4
5
6
7
8
9
10
10
20
30
40
50
60
70
80
90
100
100
200
300
400
500
600
700
800
900
1000
1000
2000
3000
4000
5000
6000
7000
8000
9000
10000

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.

27.3M

475

Hello Java Program for Beginners

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() After the specified amount of time, sleep is
methods completed.

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..."+amount);

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...Ac balance is"+this.amount);
}

synchronized void deposit(int amount){


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

class Test{
public static void main(String args[]){
final Customer c=new Customer();
new Thread(){
public void run(){c.withdraw(15000);}
}.start();
new Thread(){
public void run(){c.deposit(10000);}
}.start();
}}

o/p

going to withdraw...15000
Less balance; waiting for deposit...
going to deposit...10000
deposit completed... 20000
withdraw completed...Ac balance is5000

You might also like