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

Module 1 Advanced Java Programming CSE3146 PPTs

This document provides an overview of multithreading in Java, detailing the concepts of threads, the Thread class, and the Runnable interface, along with methods for thread management and synchronization. It covers the lifecycle of threads, thread priorities, inter-thread communication, and introduces the Executor framework for efficient thread management. Additionally, it discusses the producer-consumer problem as a classic example of multi-process synchronization.

Uploaded by

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

Module 1 Advanced Java Programming CSE3146 PPTs

This document provides an overview of multithreading in Java, detailing the concepts of threads, the Thread class, and the Runnable interface, along with methods for thread management and synchronization. It covers the lifecycle of threads, thread priorities, inter-thread communication, and introduces the Executor framework for efficient thread management. Additionally, it discusses the producer-consumer problem as a classic example of multi-process synchronization.

Uploaded by

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

MODULE – 1

Multithreading in Java

1
Contents

• Multithreading Introduction
• The Thread class & Runnable Interface
• Thread Priority
• Thread Synchronization
• Inter-thread communication
• Executor Framework (Knowledge level)

2
Multithreading
• Multithreading is a Java feature that allows concurrent execution of two or more parts of a
program for maximum utilization of CPU.
• Each part of such program is called a thread.
• So, threads are light-weight processes within a process.
Threads can be created by using two mechanisms:
Method 1. Extending the Thread class
Method 2. Implementing the Runnable Interface
Multithreading
When a Java program starts, one thread known as main thread is created, which executed code
written inside the main method, if you create a thread, then those threads are created and
started by the main thread, once started they start executing code written in their run() method.
Three different kinds of issues:
• Issues, which always comes
• Issues, which comes only sometimes, but
consistent with the same input
• Issues, which is truly random
Method 1. Thread class Method 2. Runnable Interface

Thread class Runnable

Sample Class Sample Class

Thread Class vs Runnable Interface


1. If we extend the Thread class, our class cannot extend any other class because Java doesn’t support multiple
inheritance. But, if we implement the Runnable interface, our class can still extend other base classes.
2. We can achieve basic functionality of a thread by extending Thread class because it provides some inbuilt
methods like yield(), interrupt() etc. that are not available in Runnable interface.
Life cycle of a Thread (Thread States)
• According to sun, there is only 4 states in thread life cycle in java
• New,
• Runnable,
• Not-runnable and
• Terminated.
• There is no running state.

threadStates.java
Life cycle of a Thread (Thread States): The Thread Class and Methods

yield(), or Running
time out run() returns
Thread created start()
New Ready run() join() Terminated

sleep()
interrupt()
Target wait()
finished

Wait for target Wait for time Wait to be


to finish out notified
Time out notify() or
notifyAll()
Blocked
Interrupted()
th
Thread
Method 1. Syntax:
extends
Sample
Example:
Runnable
implements
Class Class_Name Implements
OtherClas

Example:
Example: thread1.java Thread
//Program Using extends to write a single-thread program.
extends
import java.lang.*;
class ThreadExample extends Thread { ThreadExample
public ThreadExample (String name) {
super (name);
}
public void run () {
System.out.println (Thread.currentThread ());
For (int i=0; i<=5; i++)
System.out.println (i);
}
}
public class thread1 {
public static void main (String args [ ]) {
ThreadExample obj = new ThreadExample ("First"); OUTPUT:
obj.start ( ); This is: Thread [main, 5, main]
System.out.println (''This is:" + Thread.currentThread ());
} Thread [First, 5, main]
}
Example: thread2.java Runnable
//Program illustrates the creation of threads using Runnable interface. implements
class ThreadExample implements Runnable {
Thread t; ThreadExample
public ThreadExample (String ThreadName) {
t = new Thread (this, ThreadName);
}
public void run () {
System.out.println (Thread.currentThread () );
for (int i =0; i <=5; i++)
System.out.println (i);
}
}
public class thread2 {
public static void main (String args [ ]) {
ThreadExample obj = new ThreadExample(“First”); OUTPUT:
obj.t.start ( ); This is: Thread [main, 5, main]
System.out.println ("This is:" + Thread.currentThread ());
}
Thread [First, 5, main]
}
The Thread Class and Methods:
The Following methods are invoked on a particular Thread object.
«interface»
java.lang.Runnable
Some methods are not available
java.lang.Thread DESCRIPTION
+Thread() Creates a default thread.
+Thread(task: Runnable) Creates a thread for a specified task.
+start(): void Starts the thread that causes the run() method to be invoked by the JVM.
+isAlive(): boolean Tests whether the thread is currently running.
+setPriority(p: int): void Sets priority p (ranging from 1 to 10) for this thread.
+join(): void Waits for this thread to finish.
+sleep(millis: long): void Puts the runnable object to sleep for a specified time in milliseconds.
+yield(): void Causes this thread to temporarily pause and allow other threads to execute.
+interrupt(): void Interrupts this thread.
The Thread Class and Methods:
The Following methods are invoked on a particular Thread object.
Sr. No. Method & Description
1 public void start()
Starts the thread in a separate path of execution, then invokes the run() method on this Thread object.
2 public void run()
If this Thread object was instantiated using a separate Runnable target, the run() method is invoked on that Runnable
object.
3 public final void setName(String name)
Changes the name of the Thread object. There is also a getName() method for retrieving the name.
4 public final void setPriority(int priority)
Sets the priority of this Thread object. The possible values are between 1 and 10.
5 public final void setDaemon(boolean on)
A parameter of true denotes this Thread as a daemon thread.
6 public final void join(long millisec)
The current thread invokes this method on a second thread, causing the current thread to block until the second thread
terminates or the specified number of milliseconds passes.
7 public void interrupt()
Interrupts this thread, causing it to continue execution if it was blocked for any reason.
8 public final boolean isAlive()
Returns true if the thread is alive
The Thread Class and Methods:
The following methods in the Thread class are static. Invoking one of the static methods
performs the operation on the currently running thread.
Sr. No. Method & Description
1 public static void yield()
Causes the currently running thread to yield to any other threads of the same priority that are waiting
to be scheduled.
2 public static void sleep(long millisec)
Causes the currently running thread to block for at least the specified number of milliseconds.
3 public static boolean holdsLock(Object x)
Returns true if the current thread holds the lock on the given Object.
4 public static Thread currentThread()
Returns a reference to the currently running thread, which is the thread that invokes this method.
5 public static void dumpStack()
Prints the stack trace for the currently running thread, which is useful when debugging a multithreaded
application.
Thread Methods: The isAlive() Method: threadisAlive.java
• It tests if this thread is alive. A thread is alive if it has been started and has not yet died.
• method used to find out the state of a thread.
• returns true: thread is in the Ready, Blocked, or Running state
• returns false: thread is new and has not started or if it is finished.

Syntax:
final boolean isAlive( )
Thread Methods: The interrupt () Method threadInterrupt.java

• If any thread is in sleeping or waiting state (i.e. sleep() or wait() is invoked), calling the
interrupt() method on the thread, breaks out the sleeping or waiting state throwing
InterruptedException.
• If the thread is not in the sleeping or waiting state, calling the interrupt() method
performs normal behavior and doesn't interrupt the thread but sets the interrupt flag to
true.
Thread Methods: The join() Method
• join() method is used for waiting the thread in execution until the thread on which join is
called is not completed. Remember, the thread which will wait is the thread in execution
and it will wait until the thread on which join method called is not completed.
• You can use the join() method to force one thread to wait for another thread to finish.

Syntax:
final void join( ) throws InterruptedException

1. Threadwithoutjoin.java
2. Threadjoin.java
Thread Methods: deprecated: stop(), suspend(), and resume() Methods
• Whenever we want to stop a thread from running state by calling stop() method of Thread class in Java.
This method stops the execution of a running thread and removes it from the waiting threads pool and
garbage collected. A thread will also move to the dead state automatically when it reaches the end of its
method. The stop() method is deprecated in Java due to thread-safety issues.
Syntax:
public final void stop()
• The suspend() method of thread class puts the thread from running to waiting state. This method isused if
you want to stop the thread execution and start it again when a certain event occurs.
Syntax:
public final void suspend()
• The resume() method of thread class is only used with suspend() method. This method is used to resume a
thread which was suspended using suspend() method. This method allows the suspended thread to start
again.

Syntax:
public final void resume()
Thread Priority: threadPriority.java

• Each thread is assigned a default priority of Thread.NORM_PRIORITY (constant of 5).


• You can reset the priority using setPriority(int priority).
• Some static integral constants for priorities included in Thread Class:

• By default, a thread has the priority level of the thread that created it.
Thread Synchronization threadnonsync.java

• In Java, the threads are executed independently to each other. These types of threads are called
as asynchronous threads. But there are two problems may be occur with asynchronous threads.
• Two or more threads share the same resource (variable or method) while only one of them can access the
resource at one time.

• Race Condition
• Resource Conflict
Thread Synchronization

If the producer and the consumer are sharing the same kind of data in a program then
either producer may produce the data faster or consumer may retrieve an order of data and
process it without its existing.

Producer Consumer Problem


threadsyncB.java
Thread Synchronization threadsyncM.java

There are two ways to synchronized the execution of code:


1. Synchronized Methods
2. Synchronized Blocks (Statements)

General form of synchronized Method is: General form of synchronized block is:
synchronized returntype MethodName (param_List) synchronized (object reference expression)
{ {
// statements in the method Body // statements to be synchronized
} }
threadInterNonCom.java

Inter-thread communication
AFTER SYNCHRONIZATION
Problem: DeadLock Solution: Inter-Thread Communication
Inter-thread
wait(),
communication notify() &
notifyAll()

wait() with timeout


Inter-thread communication threadInterCom.java
Java provide benefits of avoiding thread pooling using inter-thread communication. The wait(), notify(),
and notifyAll() methods of Object class are used for this purpose. These method are implemented
as final methods in Object, so that all classes have them. All the three method can be called only from within
a synchronized context.
• wait() tells calling thread to give up monitor and go to sleep until some other thread enters the same monitor
and call notify.
• notify() wakes up a thread that called wait() on same object.
• notifyAll() wakes up all the thread that called wait() on same object.
These methods are declared within Object, as shown here:

• final void wait( ) throws InterruptedException


• final void notify( )
• final void notifyAll( )

Producer Consumer Problem


Executor Framework
 With the traditional approach of thread creation, When we create a new thread for executing a new task cause
overhead of thread creation, In order to manage this thread life-cycle, the execution time increase respectively.
 Java has flexible thread pool implementation, called the Executor framework.
 A framework having a bunch of components that are used for managing worker threads efficiently is
referred to as Executor Framework.
 The Executor API reduces the execution of the task from the actual task to be executed through
the Executors.
 The executor framework is an implementation of the Producer-Consumer pattern.
The java.util.concurrent.Executors class provides a set of methods for creating ThreadPools of worker
threads.
 Required for efficient Java multithreading.

25
Executor Framework

public interface Executor {


void execute(Runnable command) ;
}
 Based on producer/consumer pattern
 Producers submit tasks and consumers consume tasks
 Decouples task submission from task execution

26
Executor Framework
Based on producer/consumer pattern
Decouples task submission from task execution
The value of decoupling task submission from execution allows us to easily
change the execution policy
An execution policy specifies :
 In what thread a task will execute
 In what order tasks will be executed
 How many tasks may execute concurrently
 How many tasks may be pending
 Which tasks to reject if the system is overloaded

27
Inter Thread Communication (contd…)
Producer Consumer Problem
In computing, the producer-consumer problem (also known as
the bounded-buffer problem) is a classic example of a multi-
process synchronization problem. The problem describes two
processes, the producer and the consumer, which share a
common, fixed-size buffer used as a queue.
The producer’s job is to generate data, put it into the buffer, and start
again.
At the same time, the consumer is consuming the data (i.e. removing it
from the buffer), one piece at a time.

28
Producer-Consumer Problem
// An incorrect implementation of a producer and class Producer implements Runnable {
consumer. Q q;
class Q { Producer(Q q) {
int n; this.q = q;
synchronized int get() { new Thread(this, "Producer").start();
System.out.println("Got: " + n); }
return n; public void run() {
} int i = 0;
synchronized void put(int n) { while(true) {
this.n = n; q.put(i++);
System.out.println("Put: " + n); }
} }
} }

29
class Consumer implements Runnable { class PC {
Q q; public static void main(String args[]) {
Q q = new Q();
Consumer(Q q) { new Producer(q);
this.q = q; new Consumer(q);
System.out.println("Press Control-C to stop.");
new Thread(this, "Consumer").start(); }
} }

public void run() {


while(true) {
q.get();
}
}
OUTPUT:
} Put: 1 Got: 1 Got: 1 Got: 1
Got: 1 Put:2 Put :3 Got:2
............................
.............

30
// A correct implementation of a producer and consumer.
class Q {
int n;
boolean valueSet = false;
synchronized int get() {
while(!valueSet)
try {
wait();
}
catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
System.out.println("Got: " + n);
valueSet = false;
notify();
return n;
}

31
synchronized void put(int n) {
while(valueSet)
try {
wait();
}
catch(InterruptedException e) {
System.out.println("InterruptedException caught");
}
this.n = n;
valueSet = true;
System.out.println("Put: " + n);
notify();
}
}

32
Module – 1 Completed

33

You might also like