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

Chapter Multi 5

Uploaded by

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

Chapter Multi 5

Uploaded by

ewakjira5
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 24

HARAMBEE UNIVERSITY

HOLETA CAMPUS
DEPARTMENT OF COMPUTER SCIENCE
Course Title: Java Programming
Course Code: CoSc3053
Credit Hrs: 3 ECTS: 5
Prerequisite: CoSc 2051- Object Oriented Programming
Instructor: Derartu.T (MSc)
08/12/2024 Java programming 1
Chapter 5: Multi-threading concept

 5.1. Thread vs process
 5.2. Multiple threads
 5.2.1. Thread priorities
 5.2.2. Thread synchronization

08/12/2024 Java Programming lecture Note chapter five 2


Introduction
 Human body performs variety of operations in parallel/concurrently.
 Computers also too, can perform operations concurrently
 Only computers that have multiple processors can truly execute multiple
instructions concurrently.
 by rapidly switching between activities.
 but on such computers, only single instruction can be executed at once.
 Operating systems on single-processor computers create the illusion of
concurrent execution Java makes concurrency available to you through its APIs

08/12/2024 Java Programming lecture Note chapter five 3


What are Threads?

 A piece of code that run in concurrent with other threads.


 Each thread is a statically ordered sequence of instructions. „
 Threads are being extensively used express concurrency on both single and
multiprocessors machines. „
 Programming a task having multiple threads of control – Multithreading or
Multithreaded Programming

08/12/2024 Java Programming lecture Note chapter five 4


What is Multithreading

 Multitasking allows CPU to perform multiple tasks (process, threads)
simultaneously
 Maximum (optimal) utilization of CPU.
 Multitasking can be achieved in two ways:
 Process based and
 thread based multitasking
 Multithreading is a conceptual programming paradigm where a program
(process) is divided into sub-processes, which can be implemented at same
time in parallel.
 For example, one subprogram can be used for typing while the another may
used to check spelling error.
 This is sometimes similar to dividing a task in to subtasks and assigned them
to different people for execution independently and simultaneously.
 Both are used: To reduce CPU idle time and increase system performance.
08/12/2024 Java Programming lecture Note chapter five 5
Advantage of Multithreading
Responsiveness : Multithreading an interactive application may allow a program
to continue running even if part of it is blocked or doing a lengthy operation.
Resource Sharing :Threads share the memory and the resources(code, data, and
files)of the process to which they belong.
Enhancing throughput of the system: If a process is divided into multiple threads,
and each thread function is considered as one job, then the number of jobs
completed per unit of time is increased, thus increasing the throughput of the
system.
Utilization of multi-processor architectures: Threads may be running in parallel
on different processors.

08/12/2024 Java Programming lecture Note chapter five 6


How to create Thread in java

 We know that every Java program has at least one thread called main thread.
 When a program starts, main thread starts running immediately.
 Apart from this main thread, we can also create our own threads in a program
that is called child thread.
 Every child threads create from its main thread known as parent thread
 There are two ways to create a new thread in Java:
 By extending java.lang.Thread class
 By implementing java.lang.Runnable interface

08/12/2024 Java Programming lecture Note chapter five 7


Life Cycle of Thread

 A thread can be in any of the five following states:


 Newborn State: When a thread object is created a new thread is born and said
to be in Newborn state.
 Eg.: MyThread t1 = new MyThread();
 Runnable State: If a thread is in this state it means that the thread is ready for
execution and waiting for the availability of the processor.
 If all threads in queue are of same priority then they are given time slots for
execution in round robin fashion.

08/12/2024 Java Programming lecture Note chapter five 8


Cont’d
 Running State: It means that the processor has given its time to the thread for
execution.
 A thread keeps running until the following conditions occurs.
 Thread give up its control on its own and it can happen in the following situations.
 A thread gets suspended using suspend() method which can only be revived with
resume() method.
 A thread is made to sleep for a specified period of time using sleep(time) method,
where time in milliseconds.
 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
 A thread is pre-empted by a higher priority thread

08/12/2024 Java Programming lecture Note chapter five 9


Cont’d
 Blocked State: If a thread is prevented from entering into runnable state and
subsequently running state, then a thread is said to be in Blocked state.
 Eg.: t1.sleep(500); or t1.suspend(); or t1.wait();
 Dead State: A runnable thread enters the Dead or terminated state when it completes
its task or otherwise terminates.
 Eg.: t1.stop();

08/12/2024 Java Programming lecture Note chapter five 10


Methods of Thread class

08/12/2024 Java Programming lecture Note chapter five 11


Creating Threads
 In the most general sense, you can create a thread by instantiating an
object of type Thread.
 But, Java defines two ways in which this can be accomplished:
 You can extend the Thread class, itself
 You can implement the Runnable interface.

08/12/2024 Java Programming lecture Note chapter five 12


Extending Thread

 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

08/12/2024 Java Programming lecture Note chapter five 13


creating Thread in Java demo-1

08/12/2024 Java Programming lecture Note chapter five 14


Implementing Runnable
 The second way to create a thread is to create a class that implements the
Runnable interface.
 To implement Runnable, a class need only implement a single method called
run( ), which is declared like this:
 public void run() After you create a class that implements Runnable, you will
instantiate an object of type thread from within that class.
 Next, after the new thread is created, it will not start running until you call its
start( )method, which is declared within Thread.
 In essence, start() executes a call to run( ).

08/12/2024 Java Programming lecture Note chapter five 15


Cont’d
 Which approach is recommended to define thread:
 Implementing Runnable interface is preferred one.
 Why: We will have advantage of multiple inheritance benefit.
 Eg.: class My Thread One extends My Thread Two implements Runnable
{ //code here }

08/12/2024 Java Programming lecture Note chapter five 16


Available Thread constructor (8):
 Thread t = new Thread();
 Thread t = new Thread(Runnable r);
 Thread t = new Thread(String name);
 Thread t = new Thread(Runnable r, String name);
 Thread t = new Thread(threadGroup g, String name);
 Thread t = new Thread(threadGroup g, Runnable r);
 Thread t = new Thread(threadGroup g, Runnable r, String name);
 Thread t = new Thread(threadGroup g, Runnable r, String name, long stacksize);

08/12/2024 Java Programming lecture Note chapter five 17


Controlling Threads
 Controlling threads is the art of moving them from one state to another.
 You control threads by triggering state transitions.
 Starting a thread:
 Once a Thread has been created it is started by calling start() method.
 The start() method puts the thread into the ready state.
 To start a thread we use the following syntax: thread.start();
 Stopping a thread:
 To stop a thread from running further, we may do so by calling its stop()
method.
 This causes a thread to stop immediately and move it to its dead state.
 It forces the thread to stop abruptly before its completion
 It causes premature death.
 To stop a thread we use the following syntax: thread.stop();

08/12/2024 Java Programming lecture Note chapter five 18


Cont’d
 Blocking Threads: A thread can also be temporarily suspended or
blocked from entering into the runnable and subsequently running
state,
 1. sleep(t) // blocked for „t‟ milliseconds
 2. suspend() // blocked until resume() method is invoked
 3. wait() // blocked until notify () is invoked
 sleep() Vs yield() Methods
 Calling sleep put the current running thread into the blocked state
 Calling yield does not put the running thread into the blocked state
 It causes the currently running thread to move to the ready state.
 Thus other threads are given a chance to enter the running state.

08/12/2024 Java Programming lecture Note chapter five 19


Threads Priority

 Every Java thread has a thread priority that helps the operating system to
determine the order in which threads are scheduled priorities range between:
 MIN_PRIORITY (a constant of 1)
 NORM_PRIORITY (a constant of 5, default) and
 MAX_PRIORITY (a constant of 10)
 Each new thread inherits the priority of the thread that created it.
 Note: In case two threads have the same priority, the JVM will execute
them in FIFO order.
 Java's Thread class provides methods for checking the thread‟s priority and for
modifying it.
 getPriority() method returns the integer that represents its priority.
 setPriority(INT I) method takes integer between 1-10 to change thread's
priority.
 If we pass a value outside the 1-10 range, the method will throw an error
08/12/2024 Java Programming lecture Note chapter five 20
Cont’d

08/12/2024 Java Programming lecture Note chapter five 21


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
 Then they can produce unexpected 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.

08/12/2024 Java Programming lecture Note chapter five 22


Cont’d

 Java programming language provides a very handy way of creating threads and
synchronizing their task by using synchronized blocks.
 You keep shared resources within this block
synchronized(objectidentifier){ // Access shared variables and other shared
resources; }

08/12/2024 Java Programming lecture Note chapter five 23


THE END OF CHAPTER FIVE

08/12/2024 INTRODUCTION TO DISTRIBUTED SYSTEM 24

You might also like