0% found this document useful (0 votes)
6 views14 pages

Multi Threading

Uploaded by

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

Multi Threading

Uploaded by

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

Object Oriented Programming -I (3140705)

Unit-12
Concurrency /
Multithreading

Prof. Jayesh D. Vagadiya


Computer Engineering Department
Darshan Institute of Engineering & Technology, Rajkot
[email protected]
9537133260
 Outline
Looping

Multithreading
Life Cycle of Thread
Creating a Thread
Using Thread Class
Using Runnable Interface
Join
Synchronized
What is Multithreading?
 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.
 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.
 A thread goes through various stages in its life cycle. For example, a thread is born, started,
runs, and then dies.
 Lets see the life cycle of the thread.

Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 12 – Multithreading 3


Life cycle of a Thread
 There are 5 stages in the life cycle of the Thread
new  New: A new thread begins its life cycle in the new state. It
remains in this state until the program starts the thread. It is
Program starts
also referred to as a born thread.
thread  Runnable: After a newly born thread is started, the thread
becomes runnable. A thread in this state is considered to be
k executing its task.
oc l

Th
l runnable
un gna ll  Waiting: Sometimes a thread transitions to the waiting state

rea Tas
si alA

dc k
n while the thread waits for another thread to perform a task. A
si g

om
Interval
expires
ait thread transitions back to the runnable state only when
await

ple
sleep

aw ck

tes
lo another thread signals waiting thread to continue.
 Timed waiting: A runnable thread can enter the timed
timed waiting state for a specified interval of time. A thread in this
waiting terminated
waiting state transitions back to the runnable state when that time
interval expires or when the event it is waiting for occurs.
 Terminated: A runnable thread enters the terminated state
when it completes its task or otherwise terminates.

Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 12 – Multithreading 4


Creating a Thread in Java
 There are two ways to create a Thread
1. extending the Thread class
2. implementing the Runnable interface

Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 12 – Multithreading 5


1) Extending Thread Class
 One way to create a thread is to create a new class that extends Thread, and then to create an
instance of that class.
 The extending class must override the run( ) method, which is the entry point for the new
thread.
 It must also call start( ) to begin execution of the new thread.
class NewThread extends Thread { class ExtendThread {
NewThread() { public static void main(String args[]) {
super("Demo Thread"); new NewThread(); // create a new thread
System.out.println("Child thread: " + this); try {
start(); // Start the thread for (int i = 5; i > 0; i--) {
} System.out.println("Main Thread: " + i);
public void run() { Thread.sleep(1000);
try { }
for (int i = 5; i > 0; i--) { } catch (InterruptedException e) {
System.out.println("Child Thread: " + i); System.out.println("Main thread
Thread.sleep(500); interrupted.");
} }
} catch (InterruptedException e) { System.out.println("Main thread exiting.");
System.out.println("Child interrupted."); }
} }
System.out.println("Exiting child thread.");
}}

Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 12 – Multithreading 6


2) Implementing Runnable Interface
 To implement thread using Runnable interface, Runnable interface needs to be
implemented by the class.
class NewThread implements Runnable
 Class which implements Runnable interface should override the run() method which
containts the logic of the thread.
public void run( )
 Instance of Thread class is created using following constructor.
Thread(Runnable threadOb, String threadName);
 Here threadOb is an instance of a class that implements the Runnable interface and the
name of the new thread is specified by threadName.
 start() method of Thread class will invoke the run() method.

Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 12 – Multithreading 7


Example Runnable Interface

Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 12 – Multithreading 8


Thread using Executor Framework
 Steps to execute thread using Executor Framework are as follows:
1. Create a task (Runnable Object) to execute
2. Create Executor Pool using Executors
3. Pass tasks to Executor Pool
4. Shutdown the Executor Pool

Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 12 – Multithreading 9


Example Executable Framework
class Task implements Runnable { import java.util.concurrent.*;
private String name;
public Task(String s) { public class ExecutorThreadDemo {
name = s; public static void main(String[] args) {
} Runnable r1 = new Task("task 1");
public void run() { Runnable r2 = new Task("task 2");
try { Runnable r3 = new Task("task 3");
for (int i = 1; i<=5; i++) { Runnable r4 = new Task("task 4");
System.out.println(name+ Runnable r5 = new Task("task 5");
" - task number - "+i); ExecutorService pool =
Thread.sleep(1000); Executors.newFixedThreadPool(3);
} pool.execute(r1);
System.out.println(name+" pool.execute(r2);
complete"); pool.execute(r3);
} pool.execute(r4);
catch(InterruptedException e) { pool.execute(r5);
e.printStackTrace(); pool.shutdown();
} }
} }
}

Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 12 – Multithreading 10


Thread Synchronization
 When we start two or more threads within a program, there may be a situation when multiple
threads try to access the same resource and finally they can produce unforeseen result due to
concurrency issues.
 For example, if multiple threads try to write within a same file then they may corrupt the data
because one of the threads can override data or while one thread is opening the same file at
the same time another thread might be closing the same file.
 So there is a need to synchronize the action of multiple threads and make sure that only one
thread can access the resource at a given point in time.
 Java programming language provides a very handy way of creating threads and
synchronizing their task by using synchronized methods & synchronized blocks.

Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 12 – Multithreading 11


Problem without synchronization (Example)
class Table { class MyThread1 extends Thread {
void printTable(int n) { Table t;
for (int i = 1; i <= 5; i++) { MyThread1(Table t) {
System.out.print(n * i + " "); this.t = t;
try { }
Thread.sleep(400); public void run() {
} catch (Exception e) { t.printTable(5);
System.out.println(e); }
} }
}
}
}

class MyThread2 extends Thread { public class TestSynchronization {


Table t; public static void main(String args[]){
MyThread2(Table t) { Table obj = new Table();
this.t = t; MyThread1 t1 = new MyThread1(obj);
} MyThread2 t2 = new MyThread2(obj);
public void run() { t1.start();
t.printTable(100); t2.start();
} }
} }
Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 12 – Multithreading 12
Solution with synchronized method
class Table { class MyThread1 extends Thread {
synchronized void printTable(int n) { Table t;
for (int i = 1; i <= 5; i++) { MyThread1(Table t) {
System.out.print(n * i + " "); this.t = t;
try { }
Thread.sleep(400); public void run() {
} catch (Exception e) { t.printTable(5);
System.out.println(e); }
} }
}
}
}

class MyThread2 extends Thread { public class TestSynchronization {


Table t; public static void main(String args[]){
MyThread2(Table t) { Table obj = new Table();
this.t = t; MyThread1 t1 = new MyThread1(obj);
} MyThread2 t2 = new MyThread2(obj);
public void run() { t1.start();
t.printTable(100); t2.start();
} }
} }
Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 12 – Multithreading 13
Solution with synchronized blocks
class Table { class MyThread1 extends Thread {
void printTable(int n) { Table t;
for (int i = 1; i <= 5; i++) { MyThread1(Table t) {
System.out.print(n * i + " "); this.t = t;
try { }
Thread.sleep(400); public void run() {
} catch (Exception e) { synchronized (t) {
System.out.println(e); t.printTable(5);
} }
} }
} }
}
class MyThread2 extends Thread {
Table t;
MyThread1(Table t) { public class TestSynchronization {
this.t = t; public static void main(String args[]){
} Table obj = new Table();
public void run() { MyThread1 t1 = new MyThread1(obj);
synchronized (t) { MyThread2 t2 = new MyThread2(obj);
t.printTable(100); t1.start();
} t2.start();
} }
} }
Prof. Jayesh D. Vagadiya #3140705 (OOP-I)  Unit 12 – Multithreading 14

You might also like