(AJP) Chapter 3

Download as pptx, pdf, or txt
Download as pptx, pdf, or txt
You are on page 1of 32

COLLEGE OF COMPUTING AND

INFORMATICS

DEPARTMENT OF SOFTWARE
ENGINEERING

ADVANCED PROGRAMMING IN JAVA [SENG-2033]

BY SAMSON R.
Chapter three
Multithreading
Contents

 Introduction.
 Threads in Java.
 Threads life cycle.
 Threads Priority.
 Threads synchronization.
 Deadlocks.
Introduction

 In a networked world, it is common practice to share resources among


multiple users.
 Therefore application programs designed to be deployed in a network
should be designed to serve multiple users requests simultaneously.
 Even on desktop computers, users typically run multiple applications and
carry out some operations in the background (e.g., printing) and some in the
foreground (e.g., editing) simultaneously.
 Modern operating systems hold more than one activity (program) in
memory and the processor can switch among all to execute them. This
simultaneous occurrence of several activities on a computer is known as
multitasking.
Cont..

 Multitasking results in effective and simultaneous utilization of various


system resources such as processors, disks, and printers.
 we focus on learning how to write an application containing multiple
tasks (i.e., objects containing operations to be performed) that can be
executed concurrently.
 In Java, this is realized by using multithreading techniques.
DEFINING THREADS

 To understand multithreading, the concepts process and thread


must be understood.
 A process is a program in execution.
 A process may be divided into a number of independent units
known as threads.
 A thread is a dispatchable unit of work.
 Threads are light-weight processes within a process .
 A process is a collection of one or more threads and associated
system resources.
Cont..

 The difference between a process and a thread is:

 A process may have a number of threads in it.


 A thread may be assumed as a subset of a process.
Cont..

 If two applications are run on a computer (MS Word, MS Access), two


processes are created.
 Multitasking of two or more processes is known as process-based
multitasking.
 Multitasking of two or more threads is known as thread-based multitasking.
 The concept of multithreading in a programming language refers to thread-
based multitasking.
 Process-based multitasking is totally controlled by the operating system.
 But thread-based multitasking can be controlled by the programmer to some
extent in a program.
THREADS IN JAVA

 Threads are objects in the Java language. They can be created by


using two different mechanisms.

1. Create a class that extends the standard Thread class.


2. Create a class that implements the standard runnable interface.
 That is, a thread can be defined by

 extending the java.lang.Thread class or by


 implementing the java.lang.Runnable interface
Cont..
Extending the Thread Class
 The steps for creating a thread by using the first mechanism are:
1. Create a class by extending the Thread class and override the run()method:
class MyThread extends Thread {
public void run() {
// thread body of execution
}}
2. Create a thread object:
MyThread thr1 = new MyThread();
3. Start Execution of created thread:
thr1.start();
Cont..
Cont..

 The class MyThread extends the standard Thread class to


gain thread properties through inheritance.
 The user needs to implement their logic associated with the
thread in the run() method, which is the body of thread.
 The objects created by instantiating the class MyThread are
called threaded objects.
 Even though the execution method of thread is called run,
we do not need to explicitly invoke this method directly.
Cont..
Implementing the Runnable Interface
The steps for creating a thread by using the second mechanism are:
1. Create a class that implements the interface Runnable and override run()method:
class MyThread implements Runnable {
public void run() {
// thread body of execution
}}
2. Creating Object:
MyThread myObject = new MyThread();
3. Creating Thread Object:
Thread thr1 = new Thread(myObject);
4. Start Execution:
thr1.start();
Cont..
Cont..
 The class MyThread implements standard Runnable interface and
overrides the run()method and includes logic associated with the
body of the thread.
 The objects created by instantiating the class MyThread are
normal objects.
 Therefore, we need to create a generic Thread object and pass
MyThread object as a parameter to this generic object.
 As a result of this association, threaded object is created.
 In order to execute this threaded object, we need to invoke its
start() method which sets execution of the new thread.
THREAD LIFE CYCLE
 During its life cycle the thread moves from one state to
another depending on the operation performed.
 A Java thread can be in one of the following states:
NEW
A thread that is just instantiated is in new state.
RUNNABLE.
If a thread is in this state, it means that the thread is ready for
execution and waiting for the availability of the processor.
Cont..

RUNNING.
 It means that the processor has given its time to the thread for execution.
 A thread keeps running until the following condition occurs.
A. Thread give up its control by its own.
i. get suspended by suspend() method which can only be revived by
resume() method.
ii. A thread is made to sleep for a specified period of time using
sleep(time) method, where time is in milliseconds.
iii. A thread is made to wait for some event to occur using wait() method.
In this case a thread can be scheduled to run again using notify() method.

B. A thread is pre-empted by a higher priority thread.


Cont..
BLOCKED
If a thread is prevented from entering into runnable and
running state.

DEAD
A thread that has exited is in this state.
Cont..
Cont..
Cont..
 When the object of a user Thread class is created, the thread moves to
the NEW state.
 After invocation of the start() method, the thread shifts from the NEW
to the ready (RUNNABLE) state and is then dispatched to running
state by the JVM thread scheduler.
 After gaining a chance to execute, the run() method will be invoked.
 It should be noted that when the run() method is invoked directly
(explicitly in the program), the code in it is executed by the current
thread and not by the new thread (as the thread object is not assigned
to the virtual machine scheduler).
Cont..
 Depending on program operations or invocation of methods such as wait(),
sleep(), and suspend()or an I/O operation, the thread moves to the
WAITING, SLEEPING, and BLOCKED states respectively.
 It should be noted that the thread is still alive.
 After the completion of an operation that blocked it (I/O or sleep) or
receiving an external signal that wakes it up, the thread moves to ready state.
Then the JVM thread scheduler moves it to running state in order to
continue the execution of remaining operations.
 When the thread completes its execution, it will be moved to
TERMINATED state.
 A dead thread can never enter any other state, not even if the start() method
is invoked on it.
Sample code
class thread2 extends Thread{ class test {
public static void main(String[] args)
public void run()
{
{
System.out.println("thread 2 is thread2 th=new thread2();
running..."); thread3 th2=new thread3();
}}
class thread3 extends Thread{
th.start();
public void run()
th2.start();
{
System.out.println("thread 3 is
running..."); }}
}}
Cont..
 A close observation of the output of two different runs reveals
that the execution/completion of threads does not need to be in
the order of their start.
 Because of various operations that are performed within JVM,
threads, and different applications running at different times, it
is hard to predict the precise time at which context-switching
occurs.
 It is possible to enforce the order of execution to some extent
by setting different priorities for threads.
THREAD PRIORITY
 In Java, all the thread instances the developer created have the
same priority, which the process will schedule fairly without
worrying about the order.
 It is possible to control the priority of the threads by using the
Java APIs.
 The Thread.setPriority(…)method serves this purpose.
 The Thread class provides 3 constants value for the priority:

MIN_PRIORITY = 1, NORM_PRIORITY = 5, MAX_PRIORITY =


10
Sample code
class thread2 extends Thread{ class test {
public static void main(String[] args)
public void run()
{
{
System.out.println("thread 2 is thread2 th=new thread2();
running..."); thread3 th2=new thread3();
}} th. setPriority(10);
class thread3 extends Thread{
th2. setPriority(1);
public void run()
th.start();
{
System.out.println("thread 3 is th2.start();
running...");
}} }}
Java Thread pool
 It represents a group of threads that are waiting for the job and reuse
many times.
 Starting a new thread for each task could limit throughput and cause
poor performance.
 Using a thread pool is an ideal way to manage the number of tasks
executing concurrently.
 In case of thread pool, a group of fixed size threads are created.
 A thread from the thread pool is pulled out and assigned a job by the
service provider.
 After completion of the job, thread is contained in the thread pool
again.
Java Thread pool
Class Test1 implements Runnable{
public void run(){
for(int i=0;i<100;1++){
Thread.sleep(200);
System.potprintln(i);
}}}
Class Test2 implements Runnable{
public void run(){
for(int i=0;i<100;i++){
Thread.sleep(200);
System.potprintln(i*10);
}}}
Class Threadpool[
Public static void main(String[] args){
ExecutorService executor=Executors.newFixedThreadPool(2);
exector.execute(new Test1());
exector.execute(new Test2())
executor.shutdown();
}}
What if the size was Executor.newFixedThreadPool(1) or Executor.newCachedThreadPool()
Java Thread Synchronization
 Thread synchronization is to coordinate the execution of the
dependent threads.
 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.
 A shared resource may become corrupted if it is accessed
simultaneously by multiple threads.
 So, synchronization is used to prevent thread interference and to
prevent consistency problem.
Java Thread Synchronization
public class AccountWithoutSync {
private static Account account = new Account();
public static void main(String[] args) {
ExecutorService executor = Executors.newCachedThreadPool();
for (int i = 0; i < 100; i++) {
executor.execute(new AddAPennyTask());}
executor.shutdown();
while (!executor.isTerminated()) { }
System.out.println("What is balance? " + account.getBalance());}
private static class AddAPennyTask implements Runnable {
public void run() {
Account.deposit(1);
}
Class Account{
Int balance=0;
Int deposit(int amount){
Int newbalance=balance+amout; Thread.sleep(100); balance=newbalance;
return balance ;
}
}
Java Thread Synchronization
 There are two types of thread synchronization mutual exclusive and
inter-thread communication.
 Mutual Exclusive helps keep threads from interfering with one
another while sharing data.
 Mutual Exclusive
 Synchronized method.
 Synchronized block.
 static synchronization.
Concept of Lock in Java
Synchronization is built around an internal entity known as the lock or
monitor.
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.
Deadlock
 Sometimes two or more threads need to acquire the locks on several
shared objects. This could cause a deadlock .
 Deadlock can occur in a situation when a thread is waiting for an
object lock, that is acquired by another thread and second thread is
waiting for an object lock that is acquired by first thread.
 Since, both threads are waiting for each other to release the lock, the
condition is called deadlock.
 Thread 1 has acquired a lock on object1, and Thread 2 has acquired a lock
on object2. Now Thread 1 is waiting for the lock on object2, and Thread 2 for the lock on
object1 so that neither continue

You might also like