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

Thread - Java

The document discusses the concept of threads in Java, including how to create and manage them using the Runnable interface, thread priorities, and synchronization techniques. It explains methods like start, run, yield, join, and sleep, as well as the importance of synchronized blocks and methods to prevent data inconsistency in multi-threaded environments. Additionally, it covers inter-thread communication using wait, notify, and notifyAll methods.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
15 views

Thread - Java

The document discusses the concept of threads in Java, including how to create and manage them using the Runnable interface, thread priorities, and synchronization techniques. It explains methods like start, run, yield, join, and sleep, as well as the importance of synchronized blocks and methods to prevent data inconsistency in multi-threaded environments. Additionally, it covers inter-thread communication using wait, notify, and notifyAll methods.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 43

Thread

Multitasking
Searching File By Thread
Thread : Flow of execution. Separate JOb.
Thread Scheduler is the part of JVM for Schedule the thread.
IMPORTANT

t.start()--> Create a new Thread which is responsible for run method


But in the case t.run() won’t be created, run method will be executed just like a normal method
call by method. If the above run

T.S
CASE STUDY

WHICH APPROACH IS BEST FOR DEFINE A THREAD

AMONG TWO WAYS DEFINE A THREAD IMPLEMENTS RUNNABLE APPROACH IS


RECOMMENDED.

1. IN FIRST APPROACH WE CAN NOT EXTEND ANY OTHER CLASS.AND WE


ARE MISSING INHERITANCE BENEFIT. SO THAT'S WHY IMPLEMENT
RUNNABLE.
THIRD WAY TO CREATE A THREAD.
THREAD PRIORITY VALID RANGE

Constant for PRIORITY.

If the programmer does not set the PRIORITY then the JVM assigns the PRIORITY for the
thread.

Thread scheduler will use PRIORITY while allocating processors . the thread which has highest
priority then the higher PRIORITY will get the chance. If the 2 thread have same priority its
depend on thread scheduler
Thread PRIORITY for main is 5.

And for other threads inherit the parent thread PRIORITY.


We can prevent thread execution by using yield sleep join

Yield method causes to pause the current executing thread to give the chance for the waiting
thread for the same priority . if there is no waiting and all waiting threads then the same thread
can continue its execution.

If the multiple threads are waiting for the same priority then which waiting thread gets the
change . we can not expect it. It depends on the thread scheduler or jvm.
The thread which is yielded , when it will get the chance once again it depends on the thread
scheduler and we can’t exactly.
PROTOTYPE FOR YIELD METHOD

If YIELD METHOD called in run method


JOIN

If a thread wants to wait until completing some other thread then we should go far JOIN
METHOD.

if t1. Executes t2 join then immediately t1 will be entered into the waiting state until t2
completes. Once t2 completes then t1 can continue its execution.
SLEEP

If a thread don't want any operation for a particular time then we should go far sleep
method

HOW THREAD INterrupted.

A thread can interpret a sleeping or waiting by using the interpret method of thread class.
package com.finesse.ethereumcoldwallet;

/***
* @author Pawan Maurya
* @since July 22, 2020
*/
public class ThreadInterrupted {
public static void main(String[] args) {
Thread thread = new Thread(() -> {
for (int i = 0; i < 10000; i++) {
System.out.println(i);
}
try {
System.out.println("Going to sleep");
Thread.sleep(5000);
} catch (InterruptedException e) {
System.out.println("interrupt");
}
});
thread.start();
thread.interrupt();
System.out.println("Main thread end");
}
}
Synchronized
Class and variable cant be synchronized

Synchronized iis a modifier only for method and block but not for class and variable

If the multiple threads are trying to operate simultaneously and on the same java object then there
may be a chance of data consistency. Then we should go for synchronized keyword, if a method and
block synchronized then at a time only one thread allow to execute,
Disadvantage. performance issue. Increase waiting time of thread.

Synchronized LOCK

Synchronization concept using lock. Every object in


Internally

java has a unique lock. Whenever we are using


Synchronized keyword then only lock concept will come,

If a thread wants to execute Synchronized method and the


given object first it has to get lock of the object once thread
gets the lock then it is allowed to execute in any
Synchronized method on the object, once method execution
completes automatically thread releases a lock. Acquiring
and releasing locks internally take care of JVM.
/***
* @author Pawan Maurya
* @since July 26, 2020
*/

class Display {
synchronized void wish(String name) {
for (int i = 0; i < 10; i++) {
System.out.print("Hello Good morning : ");
try {
Thread.sleep(1000);
} catch (InterruptedException ignored) {
}
System.out.println(name);
}
}
}

class MyThread extends Thread {

private String name;


private Display display;

MyThread(String name, Display display) {


this.display = display;
this.name = name;
}

@Override
public void run() {
display.wish(name);
}
}

public class SynchronizedDemo {


public static void main(String[] args) {
Display display = new Display();
MyThread myThread1 = new MyThread("Pawan", display);
MyThread myThread2 = new MyThread("Ankit", display);
myThread1.start();
myThread2.start();
}
}

If we do not declare the wish method Synchronized then both threads will execute simultaneously then we will get
irregular output.

If we declare a wish method as Synchronized then only one thread executes at a time and we will get regular
output.

CASE STUDY
public class SynchronizedDemo {
public static void main(String[] args) {
Display display1 = new Display();
Display display2 = new Display();
MyThread myThread1 = new MyThread("Pawan", display1);
MyThread myThread2 = new MyThread("Ankit", display2);
myThread1.start();
myThread2.start();
}
}

Even though “wish” method is SynchronizedDemo because thread are operating on different
java object.

If multiple threads are operating on the same object then Synchronize required.
LOCK IN JAVA

Class level LOCK

Every class in java has a unique lock which is


nothing but class level lock.

When a thread
If a thread wants to execute a static Synchronized method then thread required class level
lock. Once a thread has class level lock then it is allowed to execute any static Synchronized
method of that class.

Once method execution completes then automatically thread releases a lock.

While a thread executing static synchronized then the remaining thread not allowed to
execute any static synchronized. Then the remaining thread is allowed to execute the
following method simultaneously.
If few lines of the code require synchronization then it is not recommended to declare the
method as synchronized. We have to enclose those few lines of the code synchronized block.

The main advantage of synchronization of the block is its reduced waiting time of thread and
improved performance of the system.

HOW TO DECLARED LOCK


/***
* @author Pawan Maurya
* @since July 26, 2020
*/

class Display {

void wish(String name) {


synchronized (this) {
for (int i = 0; i < 10; i++) {
System.out.print("Hello Good morning : ");
try {
Thread.sleep(1000);
} catch (InterruptedException ignored) {
}
System.out.println(name);
}
}
}
}

class MyThread extends Thread {

private String name;


private Display display;

MyThread(String name, Display display) {


this.display = display;
this.name = name;
}

@Override
public void run() {
display.wish(name);
}
}

public class SynchronizedDemo {


public static void main(String[] args) {
Display display1 = new Display();
MyThread myThread1 = new MyThread("Pawan", display1);
MyThread myThread2 = new MyThread("Ankit", display1);
myThread1.start();
myThread2.start();
}
}
/***
* @author Pawan Maurya
* @since July 26, 2020
*/

class Display {

void wish(String name) {


synchronized (Display.class) {
for (int i = 0; i < 10; i++) {
System.out.print("Hello Good morning : ");
try {
Thread.sleep(1000);
} catch (InterruptedException ignored) {
}
System.out.println(name);
}
}
}
}

class MyThread extends Thread {

private String name;


private Display display;

MyThread(String name, Display display) {


this.display = display;
this.name = name;
}

@Override
public void run() {
display.wish(name);
}
}

public class SynchronizedDemo {


public static void main(String[] args) {
Display display1 = new Display();
Display display2 = new Display();
MyThread myThread1 = new MyThread("Pawan", display1);
MyThread myThread2 = new MyThread("Ankit", display2);
myThread1.start();
myThread2.start();
}
}

Lock concept only applicable for class and object , not with primitive.

FAQ
If a multiple thread operating on the same java
object then three may be a chance of data
inconsistency problem this is called race condition.
We can overcome this problem by using
synchronized keywords.
A Object can acquire multiple lock

Synchronized statement

The statements present in Synchronized method


and Synchronized block are called synchronized
statements.
INTERCOMMUNICATION BETWEEN
THREAD.

TWO THREAD CAN COMMUNICATE EACH


OTHER BY USING WAIT , NOTIFY, NOTIFY
ALL.
The thread which is accepting the update is
responsible for the wait method then immediately
into waiting state.

The thread which is responsible to perform


updation after performing updation, then it is
responsible to call notify method. Then the waiting
will get notification and its execution with those
updated items.

THIS METHOD PRESENT IN OBJECT CLASS


NOT IN THREAD CLASS.
TO CALL WAIT < NOTIFY AND NOTIFY ALL,
METHODs on any object, thread should be owner of the
object that thread should has lock of that object that is
thread should be inside synchronized area hence we can call
synchronized area otherwise we will get
IllegalMonitorSTATEEXCETION.

vide(10/19) 45:00 impl

You might also like